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

What is the PUB/SUB pattern in Redis

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

Share

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

This article mainly explains "what is the PUB/SUB pattern in Redis". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "what is the PUB/SUB pattern in Redis".

Redis provides publish / subscribe function

The difference between redis and rabbitMQ publish and subscribe features:

Redis publish subscription is broadcast mode, redis publishes a message, all consumers can consume, while rabbitMQ queue, publish a message can notify all subscribers, but this can have a subscriber to consume message.

Redis messages are not cached, and no consumer consumption will disappear after redis publishes the message, while rabbitMQ will always exist after it is not consumed.

Redis messages can be persistent (depending on how redis is persisted and user logic), and rabbitMQ messages disappear after consumption.

Redis can set the key and action for publishing messages (described later).

In a distributed environment, redis can publish messages for all dynamically created instance nodes.

Redis publish / subscribe application scenario:

The configuration of the configuration center in the distributed environment changes, notifying all instance nodes to refresh the configuration.

Notify all databases to synchronize data when data changes in a multi-database environment.

The third party docks one-to-many scenarios and broadcasts all third-party services at one time.

……

Java function realization

Enable publish / subscribe function in redis configuration:

The detailed configuration of redis publish / subscribe configuration notify-keyspace-events can be found in the redis configuration file.

Create a springboot web project and add a RedisMsgPubSubListener listener:

Import lombok.extern.slf4j.Slf4j;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.data.redis.connection.Message;import org.springframework.data.redis.connection.MessageListener;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.stereotype.Component;@Slf4j@Componentpublic class RedisMsgPubSubListener implements MessageListener {@ Autowired private RedisTemplate redisTemplate @ Override public void onMessage (Message message, byte [] pattern) {System.out.println ("listening for changes in YCYC data in redis:" + redisTemplate.opsForHash () .values ("YCYC"));}}

Add redis configuration and install it in the listener:

Import com.fasterxml.jackson.annotation.JsonAutoDetect;import com.fasterxml.jackson.annotation.PropertyAccessor;import com.fasterxml.jackson.databind.ObjectMapper;import com.yc.web.base.interceptor.RedisMsgPubSubListener;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.data.redis.connection.RedisConnectionFactory;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.data.redis.listener.PatternTopic;import org.springframework.data.redis.listener.RedisMessageListenerContainer Import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;import org.springframework.data.redis.serializer.StringRedisSerializer;@Configurationpublic class RedisConfig {@ Bean public RedisTemplate redisTemplate (RedisConnectionFactory connectionFactory) {RedisTemplate template = new RedisTemplate (); template.setConnectionFactory (connectionFactory); / / 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.afterPropertiesSet (); return template } @ Bean public RedisMessageListenerContainer container (RedisConnectionFactory connectionFactory, MessageListenerAdapter listenerAdapter) {RedisMessageListenerContainer container = new RedisMessageListenerContainer (); container.setConnectionFactory (connectionFactory); / / container.addMessageListener (listenerAdapter, new PatternTopic ("_ _ keyevent@*:hset")); container.addMessageListener (listenerAdapter, new PatternTopic ("_ _ keyspace@*:YCYC")); return container @ Bean public MessageListenerAdapter listenerAdapter (RedisMsgPubSubListener receiver) {return new MessageListenerAdapter (receiver);}}

Add a test Controller:

Import com.yc.web.base.annotations.NoRepeatSubmit;import com.yc.web.base.config.ResultInfo;import io.swagger.annotations.Api;import io.swagger.annotations.ApiOperation;import lombok.extern.slf4j.Slf4j;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.RequestMapping;import org.springframework.web.bind.annotation.RestController @ Slf4j@Api (description = "redis") @ RestController@RequestMapping ("/ redis") public class RedisController {@ Autowired private RedisTemplate redisTemplate; @ ApiOperation (response = ResultInfo.class, value = "setRedis", notes = "setRedis") @ GetMapping (value = "/ setRedis") @ NoRepeatSubmit public ResultInfo setRedis () throws Exception {/ redisTemplate.opsForValue () set ("YCYC", "YC_chat") RedisTemplate.opsForHash () .put ("YCYC", "YC1", System.currentTimeMillis ()); redisTemplate.opsForHash () .put ("YCYC", "YC2", System.currentTimeMillis ()); / / redisTemplate.convertAndSend ("YCYC", "YC_chat"); System.out.println ("added successfully"); return ResultInfo.Success ();}}

Start the project test, set the data in hash format to redis in Controller, and the data changes in redis will be monitored in RedisMsgPubSubListener:

Add successful listening to changes in YCYC data in redis: [1571367514510,1571367514524] listening to changes in YCYC data in redis: [1571367514510,1571367514524] Thank you for reading. The above is the content of "what is PUB/SUB mode in Redis". After the study of this article, I believe you have a deeper understanding of what the PUB/SUB mode in Redis is, and the specific use needs to be verified by 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: 0

*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