第八篇:Spring Boot使用Redis實現訊息佇列
阿新 • • 發佈:2018-12-12
目前常用的訊息佇列大概有三種類型,RabbitMQ等AMQP系列, Kafka, Redis等key-value系列,它們的使用場景分別是:
1.RabbitMQ:相對重量級高併發的情況,比如資料的非同步處理,任務的序列執行等.
2.Kafka:基於Pull的模式來處理,具體很高的吞吐量,一般用來進行,日誌的儲存和收集.
3.Redis:輕量級高併發,實時性要求高的情況,比如快取,秒殺,及時的資料分析(ELK日誌分析框架,使用的就是Redis).
這篇文章主要講述Spring Boot基於Redis快速實現訊息佇列。
環境依賴
在pom檔案,加入spring-boot-starter-data-redis依賴:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
註冊StringRedisTemplate
@Configuration
public class PublisherConfig {
@Bean
public StringRedisTemplate getRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
return new StringRedisTemplate(redisConnectionFactory);
}
}
Service
訊息生產者,注入redisTemplate,用convertAndSend傳送訊息
@Service
public class PublisherService {
@Autowired
private StringRedisTemplate redisTemplate;
public String sendMessage(String name) {
try {
redisTemplate. convertAndSend("TOPIC_USERNAME", name);
return "訊息傳送成功了";
} catch (Exception e) {
e.printStackTrace();
return "訊息傳送失敗了";
}
}
}
Controller
請求時傳送訊息
@RestController
@RequestMapping("publisher")
public class PublisherController {
@Autowired
private PublisherService publisherService;
@RequestMapping("{name}")
public String sendMessage(@PathVariable("name") String name) {
return publisherService.sendMessage(name);
}
}
消費者
建立一個接收訊息的類,可以繼承MessageListener,也可以不繼承
@Component
public class Receiver implements MessageListener {
private static Logger logger = LoggerFactory.getLogger(Receiver.class);
@Autowired
private StringRedisTemplate redisTemplate;
@Override
public void onMessage(Message message, byte[] pattern) {
RedisSerializer<String> valueSerializer = redisTemplate.getStringSerializer();
String deserialize = valueSerializer.deserialize(message.getBody());
logger.info("Received <" + message + ">");
}
}
@Component
public class Receiver {
private static final Logger logger = LoggerFactory.getLogger(Receiver.class);
public void receiveMessage(String message) {
logger.info("Received <" + message + ">");
}
}
訊息訂閱者配置類
@Configuration
@AutoConfigureAfter({Receiver.class})
public class SubscriberConfig {
/**
* 訊息監聽介面卡,注入接受訊息方法,輸入方法名字 反射方法
*
* @param receiver
* @return
*/
@Bean
public MessageListenerAdapter getMessageListenerAdapter(Receiver receiver) {
return new MessageListenerAdapter(receiver, "receiveMessage"); //當沒有繼承MessageListener時需要寫方法名字
}
/**
* 建立訊息監聽容器
*
* @param redisConnectionFactory
* @param messageListenerAdapter
* @return
*/
@Bean
public RedisMessageListenerContainer getRedisMessageListenerContainer(RedisConnectionFactory redisConnectionFactory, MessageListenerAdapter messageListenerAdapter) {
RedisMessageListenerContainer redisMessageListenerContainer = new RedisMessageListenerContainer();
redisMessageListenerContainer.setConnectionFactory(redisConnectionFactory);
redisMessageListenerContainer.addMessageListener(messageListenerAdapter, new PatternTopic("TOPIC_USERNAME"));
return redisMessageListenerContainer;
}
}
測試
由logger可以看出,接收者接收到了傳送者的訊息。