import com.example.rabbitmqdemo.Service.RabbitmqService;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
@RestController
public class RabbitmqController {
@Autowired
private RabbitmqService rabbitmqService;
@Autowired
private RabbitTemplate rabbitTemplate;
@RequestMapping( "/sendWork" )
public Object sendWork( ) throws IOException, TimeoutException {
//rabbitmqService.sendWork( ) ;
// 创建连接
ConnectionFactory factory = new ConnectionFactory( ) ;
// 设置 RabbitMQ 的主机名
factory.setHost( "192.168.8.190" ) ;
factory.setUsername( "user" ) ;
factory.setPassword( "123456" ) ;
factory.setPort( 5672 ) ;
// 创建一个连接
Connection connection = factory.newConnection( ) ;
// 创建一个通道
Channel channel = connection.createChannel( ) ;
// 指定一个队列,不存在的话自动创建
channel.queueDeclare( "queueWork2" , true, false, false, null) ;
// 发送消息
rabbitTemplate.convertAndSend( "queueWork2" , "测试work模型: " ) ;
System.out.println( "发送消息" + "测试work模型" ) ;
// 关闭频道和连接
channel.close( ) ;
connection.close( ) ;
return "发送成功..." ;
}
}
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
// 2 个消费者
@Component
public class WorkReceiveListener {
/* @RabbitListener( queues = "queue_work" )
public void receiveMessage( Object msg, Channel channel, Message message) {
// 只包含发送的消息
System.out.println( "1接收到消息:" + msg.toString( )) ;
// channel 通道信息
// message 附加的参数信息
} */
@RabbitListener( queues = "queueWork2" )
public void receiveMessage2( Object obj, Channel channel, Message message) {
// 包含所有的信息
System.out.println( "2接收到消息:" + obj.toString( )) ;
}
}
import org.springframework.amqp.core.Queue;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.context.annotation.Bean;
@SpringBootConfiguration
public class RabbitmqConfig {
// 配置一个工作模型队列
@Bean
public Queue queueWork1 ( ) {
return new Queue( "queue_work" ) ;
}
@Bean
public Queue queueWork2 ( ) {
return new Queue( "queueWork2" ) ;
}
}