创建mq发送和接收的module
发送的模块创建配置类,配置交换机、队列和绑定
@Configuration
public class SenderConfig {
@Value("${ego.updateBigAdCache.queue}")
private String contentQueue;
@Value("${ego.updateBigAdCache.exchange}")
private String exchange;
/**
* 如果没有队列,帮助创建队列。
*
* @return
*/
@Bean
public Queue queue() {
return new Queue(contentQueue);
}
@Bean
public DirectExchange directExchange() {
return new DirectExchange(exchange);
}
@Bean
// 参数名和方法名一直就是从spring容器中获取对应方法的返回值
public Binding binding(Queue queue, DirectExchange directExchange){
return BindingBuilder.bind(queue).to(directExchange).withQueueName();
}
}
发送模块创建发送工具类,指定发送消息方法
@Component
public class PublishMessage {
@Autowired
private AmqpTemplate amqpTemplate;
/**
* 异步发送消息方法
* @param exchange 交换器 接受消息发送到队列
* @param routingKey 路由key 绑定交换器和队列
* @param message 发送消息,任意数据
*/
public void asyncSenderMessage(String exchange,String routingKey,Object message){
amqpTemplate.convertAndSend(exchange,routingKey,message);
}
/**
* 同步发送消息方法
* @param exchange 交换器 接受消息发送到队列
* @param routingKey 路由key 绑定交换器和队列
* @param message 发送消息,任意数据
*/
public Object syncSenderMessage(String exchange,String routingKey,Object message){
Object result = amqpTemplate.convertSendAndReceive(exchange, routingKey, message);
return result;
}
}
yml配置客户端访问路径
spring:
application:
name: receive
rabbitmq:
host: 192.168.22.111
username: admin
password: admin
port: 5672
接收模块创建QueueListener 队列监听类,监听到的消息后消费者的后一步处理写在方法上
@RabbitListener 注解配置绑定
//更新缓存
@RabbitListener(
bindings = {@QueueBinding(
exchange = @Exchange("${ego.updateBigAdCache.exchange}"),
value = @Queue(name = "${ego.updateBigAdCache.queue}", autoDelete = "false"),
key = "${ego.updateBigAdCache.routingKey}"
)}
)
public void receiveMessageRedis(Object message) {
System.out.println("message ===== " + message);
//当删除广告的时候
if (message instanceof List){
System.out.println("删除了");
List<TbContent> tbContents = tbContentDubboService.selectAllById((List<Long>) message);
for (TbContent tbContent : tbContents) {
if (tbContent.getCategoryId().equals(categoryId)) {
cacheBigAd();
//只要有一个是大广告,执行cacheBigad后退出
return;
}
}
}
//当新增和修改的时候调用自定义redis缓存
cacheBigAd();
}
监听模块yml
spring:
application:
name: receive
rabbitmq:
host: 192.168.22.111
username: admin
password: admin
port: 5672
profiles:
active: redis,commons
dubbo:
appliation:
name: ego-rabbitmq-receive
registry:
address: zookeeper://192.168.22.10:2181
调用
spingboot中的消费者模块调用发送类的发送消息方法
@Override
public EgoResult update(TbContent tbContent) {
tbContent.setUpdated(new Date());
int index = tbContentDubboService.update(tbContent);
// 修改redis缓存耗时操作,放入mq操作
if(index==1){
if(tbContent.getCategoryId().equals(bigadId)){
publishMessage.asyncSenderMessage(exchange,routingKey,"修改广告了...");
}
return EgoResult.ok();
}
return EgoResult.error("修改失败");
}