P是生产者,C是消费者,中间是队列
springboot整合使用
引入依赖:org.springframework.boot:spring-boot-starter-amqp:1.5.8.RELEASE
添加配置:在application.properties中添加
spring.rabbitmq.host=xx.xx.xx.xx
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
添加mq配置类
@Configuration
public class RabbitConfig {
@Bean//注册一个,hello是队列名称,简单的
public Queue Queue() {
return new Queue("hello");
}
}
发送者类
@Component
public class Sender {
@Autowired
private AmqpTemplate rabbitTemplate;
public void send() {
//发送者和接收者的queue name必须一致,不然不能接收
String context = "你好 " + new Date();
System.out.println("Sender : " + context);
this.rabbitTemplate.convertAndSend("hello", context);
}
}
接收者类
@Component
@RabbitListener(queues = "hello")
public class Receiver {
@RabbitHandler
public void process(String hello) {
System.out.println("Receiver : " + hello);
}
}
使用
@Controller
@RequestMapping("/hi")
public class HelloController {
@Autowired
private Sender sender;
/**
* 测试消息
*/
@RequestMapping(value = "/sender", method = RequestMethod.GET)
@ResponseBody
public String sender() {
sender.send();
return "ok";
}
}
发送请求,控制台会打印;
使用amqp-client
在项目中添加客户端库:”com.rabbitmq:amqp-client:4.0.1”及依赖
slf4j-simple-1.7.22.jar,slf4j-api-1.7.21.jar
发送类
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
public class Send {
private final static String QUEUE_NAME = "hello";
public static void main(String[] argv) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("xx.xx.xx.xx");
factory.setUsername("guest");
factory.setPassword("guest");
factory.setPort(5672);
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
String message = "Hello World!";
channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
System.out.println(" [x] Sent '" + message + "'");
channel.close();
connection.close();
}
}
接收者类
public class Recv {
private final static String QUEUE_NAME = "hello";
public static void main(String[] argv) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("xx.xx.xx.xx");
factory.setUsername("guest");
factory.setPassword("guest");
factory.setPort(5672);
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
Consumer consumer = new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body)
throws IOException {
String message = new String(body, "UTF-8");
System.out.println(" [x] Received '" + message + "'");
}
};
channel.basicConsume(QUEUE_NAME, true, consumer);
}
}
直接运行即可;