Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Implementation of redis message queue

2025-01-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "the implementation of redis message queue". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "the implementation of redis message queue".

Method 1: read the command through list blocking, blpop or brpop

Consumer

Public class Consumer extends DemoApplicationTests {@ Test public void consume () {int timeout = 0 int timeout / never timeout String key = "test_que"; / / the first element of the list collection is the key value, and the second element is the pop-up element value When timeout returns [null] while (true) {List obj = redisTemplate.executePipelined (new RedisCallback () {@ Override public Object doInRedis (RedisConnection connection) throws DataAccessException {/ / queue no element will block the operation until the queue gets a new element or times out return connection.bLPop (timeout,key.getBytes ()) }, new StringRedisSerializer (); for (Object o:obj) {System.out.println ("-" + o);}

Producer

Public class Productor extends DemoApplicationTests {@ Test public void generateMsg () {String key = "test_que"; redisTemplate.opsForList () .leftPush (key, "hht2");}}

Method 2: spring boot used by Pub/Sub (publish / subscribe)

Dependency package

Org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-data-redis org.springframework.boot spring-boot-starter-test test org.apache.commons commons-pool2

Configuration class

@ Configuration@AutoConfigureAfter (RedisAutoConfiguration.class) @ EnableCachingpublic class RedisConfig extends CachingConfigurerSupport {/ * configure custom redisTemplate * @ return * / @ Bean RedisTemplate redisTemplate (RedisConnectionFactory redisConnectionFactory) {RedisTemplate template = new RedisTemplate (); template.setConnectionFactory (redisConnectionFactory); / / use Jackson2JsonRedisSerializer to serialize and deserialize the value of redis Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer (Object.class); ObjectMapper mapper = new ObjectMapper () Mapper.setVisibility (PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); mapper.enableDefaultTyping (ObjectMapper.DefaultTyping.NON_FINAL); serializer.setObjectMapper (mapper); template.setValueSerializer (serializer); / / use StringRedisSerializer to serialize and deserialize the key value of redis template.setKeySerializer (new StringRedisSerializer ()); template.setHashKeySerializer (new StringRedisSerializer ()); template.setHashValueSerializer (serializer); template.afterPropertiesSet () Return template;} / * Serialization customization * * @ return * / @ Bean public Jackson2JsonRedisSerializer jackson2JsonSerializer () {Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer (Object.class); / / initialize objectmapper ObjectMapper mapper = new ObjectMapper (); mapper.setSerializationInclusion (JsonInclude.Include.NON_NULL); mapper.enableDefaultTyping (ObjectMapper.DefaultTyping.NON_FINAL) Jackson2JsonRedisSerializer.setObjectMapper (mapper); return jackson2JsonRedisSerializer;} / * * message listener, using MessageAdapter to automate decoding and method proxy * * @ return * / @ Bean public MessageListenerAdapter listener (Jackson2JsonRedisSerializer jackson2JsonRedisSerializer, MessageSubscriber subscriber) {MessageListenerAdapter adapter = new MessageListenerAdapter (subscriber, "onMessage") Adapter.setSerializer (jackson2JsonRedisSerializer); adapter.afterPropertiesSet (); return adapter } / * bind the subscriber to the container * * @ param connectionFactory * @ param listenerAdapter * @ return * / @ Bean public RedisMessageListenerContainer container (RedisConnectionFactory connectionFactory, MessageListenerAdapter listener) {RedisMessageListenerContainer container = new RedisMessageListenerContainer (); container.setConnectionFactory (connectionFactory) Container.addMessageListener (listener, new PatternTopic ("/ redis/*"); return container;}}

Simulated message publishing class

@ Servicepublic class RedisPubSub {private static final Logger logger = LoggerFactory.getLogger (RedisPubSub.class); @ Autowired private RedisTemplate redisTemplate; private ChannelTopic topic = new ChannelTopic ("/ redis/pubsub"); @ Scheduled (initialDelay = 5000, fixedDelay = 10000) private void schedule () {logger.info ("publish message"); publish ("admin", "hey you must go now!") } / * param publisher * @ param message * / public void publish (String publisher, String content) {logger.info ("message send {} by {}", content, publisher); redisTemplate.convertAndSend (topic.getTopic (), content);}}

Analog message receiving class

@ Componentpublic class MessageSubscriber {Logger logger = LoggerFactory.getLogger (MessageSubscriber.class); public void onMessage (String message, String pattern) {logger.info ("topic {} received {}", pattern, message);}}

Startup class

@ SpringBootApplication@EnableSchedulingpublic class DemoApplication {public static void main (String [] args) {SpringApplication.run (DemoApplication.class, args);}} Thank you for reading. The above is the content of "the implementation of redis message queue". After the study of this article, I believe you have a deeper understanding of the implementation of redis message queue, and the specific usage still needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 280

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report