PS:生产者和消费者在两个项目中
生产者
1、maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
2.yml
spring:
application:
name: test-demo
rabbitmq:
host: 127.0.0.1
port: 5672
virtual-host: /adminPy
username: admin_py
password: 123456
connection-timeout: 1500ms
#生产端监听
publisher-confirms: true
#生产端监听
publisher-returns: true
template:
mandatory: true #该属性必须设置为true,并与publisher-returns一起联合使用才可以
publisher-confirm-type: simple
3、代码
import com.example.springcloud.entity.Order;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.core.RabbitTemplate.ConfirmCallback;
import org.springframework.amqp.rabbit.core.RabbitTemplate.ReturnCallback;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Map;
/**
* Created by py
* 2020/4/25
*/
@Component
public class RabbitSender {
@Autowired
private RabbitTemplate rabbitTemplate;
final ConfirmCallback confirmCallback = new ConfirmCallback(){
@Override
public void confirm(CorrelationData correlationData, boolean b, String s) {
System.err.println("correlationData: " + correlationData);
System.err.println("ack: " + b);
if(!b){
System.err.println("异常处理....");
}
}
};
//回调函数: return返回
final ReturnCallback returnCallback = new ReturnCallback() {
@Override
public void returnedMessage(org.springframework.amqp.core.Message message, int replyCode, String replyText,
String exchange, String routingKey) {
try {
String body = new String(message.getBody(), "utf-8");
System.err.println("body:"+body);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
System.err.println("return exchange: " + exchange + ", routingKey: "
+ routingKey + ", replyCode: " + replyCode + ", replyText: " + replyText);
}
};
//发送消息方法调用: 构建Message消息
public void send(Object message, Map<String, Object> properties) throws Exception {
MessageHeaders mhs = new MessageHeaders(properties);
Message msg = MessageBuilder.createMessage(message, mhs);
rabbitTemplate.setConfirmCallback(confirmCallback);
rabbitTemplate.setReturnCallback(returnCallback);
//id + 时间戳 全局唯一
CorrelationData correlationData = new CorrelationData("MSG-"+ new Date().getTime());
rabbitTemplate.convertAndSend("springboot-exchange", "springboot.abc", msg, correlationData);
}
//发送消息方法调用: 构建自定义对象消息
//todo 推送对象的话生产者和消费者对象的包名必须完全一致才行,否则消费者无法接收对象数据
public void sendOrder(Order order) throws Exception {
rabbitTemplate.setConfirmCallback(confirmCallback);
rabbitTemplate.setReturnCallback(returnCallback);
//id + 时间戳 全局唯一
CorrelationData correlationData = new CorrelationData("order-"+ new Date().getTime());
rabbitTemplate.convertAndSend("exchange-2", "*", order, correlationData);
}
}
import com.example.springcloud.entity.Order;
import com.example.springcloud.testdemo.rabbitConfig.RabbitSender;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* Created by py
* 2020/4/25
*/
@RequestMapping("/rabbit")
@RestController
public class RabbitController {
@Autowired
private RabbitSender rabbitSender;
private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
@RequestMapping("/send1")
public String senderMsg() throws Exception {
Map<String, Object> properties = new HashMap<>();
properties.put("number", "12345");
properties.put("send_time", simpleDateFormat.format(new Date()));
rabbitSender.send("Hello RabbitMQ For Spring Cloud",properties);
return "信息发送成功";
}
@RequestMapping("/send2")
public String sender2() throws Exception {
Order order = new Order(1,"this is order");
rabbitSender.sendOrder(order);
return "信息发送成功";
}
}
消费者:
1、maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
2、yml
spring.rabbitmq.host=127.0.0.1
spring.rabbitmq.port=5672
spring.rabbitmq.virtual-host=/adminPy
spring.rabbitmq.username=admin_py
spring.rabbitmq.password=123456
spring.rabbitmq.connection-timeout=1500ms
#手动回复信息
spring.rabbitmq.listener.direct.acknowledge-mode=manual
#设置并发数量
spring.rabbitmq.listener.simple.concurrency=5
#设置最大并发数量
spring.rabbitmq.listener.simple.max-concurrency=10
3、代码
import com.example.springcloud.entity.Order;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.Message;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.Map;
/**
* Created by py
* 2020/4/26
*/
@Component
public class RabbitRecver {
@RabbitListener(bindings=@QueueBinding(
value = @Queue(name = "springboot-queue",declare = "true",durable = "true",exclusive = "false"),
exchange = @Exchange(name = "springboot-exchange",type = "topic"),
key = "#"
))
@RabbitHandler
public void Recver(Message message, @Headers Map<String, Object> heards, Channel channel){
System.out.println(message.getPayload());
//所有消息处理后必须进行消息的ack,channel.basicAck()
Long tag = (Long)heards.get(AmqpHeaders.DELIVERY_TAG);
try {
channel.basicAck(tag , false);
} catch (IOException e) {
e.printStackTrace();
}
}
@RabbitListener(bindings =
@QueueBinding(
value = @Queue(value = "springboot.def",durable = "true",exclusive = "false"),
exchange = @Exchange(name = "exchange-2",type = "direct"),
key = "*"
)
)
@RabbitHandler
public void RecverOrder(@Payload Order order, Channel channel, @Headers Map<String,Object> heards) throws IOException {
System.out.println(order);
Long tag = (Long) heards.get(AmqpHeaders.DELIVERY_TAG);
channel.basicAck(tag,false);
}
}
PS:注意生产者和消费在order对象的包名路径完全一致,不一致消费者无法正常接收信息。