RabbitMQ和Redis在SpringBoot中的使用
- RabbitMQ
- 导入依赖
<!-- rabbtiMq,使用rabbitTemplate-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.amqp</groupId>
<artifactId>spring-rabbit-test</artifactId>
<scope>test</scope>
</dependency>
- application.yml配置
spring:
rabbitmq:
port: 5672
host: localhost
username: username
password: password
#这个配置是保证提供者确保消息推送到交换机中,不管成不成功,都会回调
publisher-confirm-type: correlated
#保证交换机能把消息推送到队列中
publisher-returns: true
virtual-host: /
#这个配置是保证消费者会消费消息,手动确认
listener:
simple:
acknowledge-mode: manual
template:
mandatory: true
- RabbitMqConfig配置文件
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
// 该类只用于Bean注入
@Configuration
public class RabbitMqConfig {
// 读取application.yml文件中的配置
@Value("${spring.rabbitmq.port}")
private int port;
@Value("${spring.rabbitmq.host}")
private String host;
@Value("${spring.rabbitmq.username}")
private String username;
@Value("${spring.rabbitmq.password}")
private String password;
@Bean
public CachingConnectionFactory connectionFactory(){
CachingConnectionFactory connectionFactory=new CachingConnectionFactory(host,port);
connectionFactory.setUsername(username);
connectionFactory.setPassword(password);
return connectionFactory;
}
@Bean
public RabbitTemplate rabbitTemplate(CachingConnectionFactory connectionFactory){
return new RabbitTemplate(connectionFactory);
}
@Bean
public Queue myQueue(){
// 默认值
return new Queue("goods");
}
@Bean
public DirectExchange myExchange(){
// 默认值
return new DirectExchange("goods");
}
@Bean
public Binding queueToExchangeBinding(Queue myQueue,DirectExchange myExchange){
return BindingBuilder.bind(myQueue).to(myExchange).with("goods");
}
}
- 实例使用
① 引入
@Autowired
private RabbitTemplate rabbitTemplate;
@Autowired
private RedisTemplate redisTemplate;
② 调用方法
【发布/订阅者模式】
生产者
//定时任务发布商品
public void sentGoods(List<Goods> list){
//首先查询数据
//生产者
for(Goods goods:list){
//指定队列
rabbitTemplate.convertAndSend("goods",goods);
}
}
消费者【使用Redis】
@RabbitListener(queues = "goods")
@RabbitHandler
public void sentGoodsToRedis(Goods goods){
String key=goods.getId().toString();
//使用Redis实现数据缓存【此处用的hash格式放入数据】
redisTemplate.opsForHash().put(key,"goods",goods);
}