application.yml:
spring:
rabbitmq:
host: 192.168.133.151
port: 5672
username: guest
password: guest
virtual-host: /
redis:
host: 127.0.0.1
启动类:
package com.lscl.rabbitmq;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.QueueBuilder;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class);
}
@Bean
public RedisTemplate redisTemplate(RedisTemplate redisTemplate){
// value可见
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
// key可见
redisTemplate.setKeySerializer(new StringRedisSerializer());
return redisTemplate;
}
// 定义测试队列
@Bean
public Queue testQueue(){
return QueueBuilder.durable("test\_queue").build();
}
}
监听器:
package com.lscl.rabbitmq.listener;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
@Component
public class TestListener {
@Autowired
private RedisTemplate redisTemplate;
@RabbitListener(queues = "test\_queue")
public void test\_queue\_confirm(Message message) {
String messageId = message.getMessageProperties().getMessageId();
if (null == messageId) {
System.out.println("消息id为null!");
return;
}
if (redisTemplate.opsForValue().setIfAbsent(messageId, new String(message.getBody()))) {
// 代表第一次消费消息
System.out.println("消息消费成功: " + new String(message.getBody()));
} else {
System.out.println("消息已经被消费过了!");
}
}
}
消息发送端:
package com.lscl.rabbitmq.controller;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
**网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。**
**[需要这份系统化资料的朋友,可以点击这里获取](https://bbs.csdn.net/topics/618540462)**
**一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!**