其他分享
首页 > 其他分享> > RabbitMq基础二之direct模式

RabbitMq基础二之direct模式

作者:互联网

生产者:product.php

$conConfig = [
	'host'		=>	'127.0.0.1',
	'port'		=>	'5672',
	'login'		=>	'sblack',
	'password'	=>	'123456',
	'vhost'		=>	'/',
];

try {
	$connection = new AMQPConnection($conConfig);
	$connection->connect();
	if(!$connection->isConnected()){
		echo 'rabbitmq connect fail';
		die();
	}
	
	//新建通道
	$channel = new AMQPChannel($connection);
	
	//使用默认exchange
	$exchange = new AMQPExchange($channel);
	for($i=6;$i<20;$i++){
		$message = [
			'name'	=> '默认交换机,消息'.$i,
			'info'	=>	'hello world',
		];
		//发送消息,为消息指定routing key,成功返回true,失败返回false
		$state = $exchange->publish(json_encode($message,JSON_UNESCAPED_UNICODE),'quue2');
		if($state){
			echo 'success'.PHP_EOL;
		}else{
			echo 'fail'.PHP_EOL;
		}
	}
	//关闭$channel
	$channel->close();
	
	//关闭连接
	$connection->disconnect();
	
} catch(Execption $e){
	echo $e->getMessage();
}

 消费者:consumer.php

$conConfig = [
	'host'		=>	'127.0.0.1',
	'port'		=>	'5672',
	'login'		=>	'sblack',
	'password'	=>	'123456',
	'vhost'		=>	'/',
];

//默认direct 模式
try {
	$connection = new AMQPConnection($conConfig);
	$connection->connect();
	if(!$connection->isConnected()){
		echo 'rabbitmq connect fail';
		die();
	}
	
	//新建通道
	$channel = new AMQPChannel($connection);
	//
	$queue = new AMQPQueue($channel);
	$queue->setName('quue2');
	$queue->setFlags(AMQP_DURABLE);
	//声明队列,不需要对Queue进行显示绑定到交换机和指定Queue的routing key
	$queue->declareQueue();
	$queue->consume(function($envelope,$queue){
		$msg = $envelope->getBody().PHP_EOL;
		error_log($msg,3,"queue.log");
	},AMQP_AUTOACK);
	
	//关闭连接
	$connection->disconnect();
	
} catch(Execption $e){
	echo $e->getMessage();
}

 

标签:direct,模式,echo,queue,connection,RabbitMq,new,channel,connect
来源: https://www.cnblogs.com/sblack/p/16360112.html