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 method of SpringBoot Redis publish and subscribe model

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

The main content of this article is to explain "what is the method of SpringBoot Redis publish and subscribe model". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Now let the editor take you to learn "what is the method of SpringBoot Redis publish and subscribe model"?

Note: the publish and subscribe mode of redis cannot persist messages. Subscribers may miss messages due to network disconnection or downtime.

Use publish subscriptions under the Redis command line

Publish release

Publishers can publish message to a specified channel with the following command

Redis > publish channel message

Subscribe subscription

Subscribers can subscribe to one or more channels with the following command, which will be created if the channel does not exist

Redis > subscribe channel [channel...]

The command for publishing and subscribing to redis is as simple as that. So how do we use publish and subscribe in springboot next?

Using the publish and subscribe function of Redis in SpringBoot

Don't mention adding dependency configuration redis information and connection pooling. If you add commons-pool2 dependencies, it will automatically help us configure redis connection pooling.

Publisher

Compared to the subscriber, the publisher's implementation is very simple, and the following ways can send message to channel.

@ Resource private RedisTemplate redisTemplate; public void publish () {/ / use advanced redisTemplate redisTemplate.convertAndSend ("channel", "message") / / using low-level connection is actually the bottom layer of redisTemplate using the following methods: redisTemplate.execute (new RedisCallback () {@ Override public Object doInRedis (RedisConnection connection) throws DataAccessException {connection.publish ("channel" .getBytes (StandardCharsets.UTF_8), "message" .getBytes (StandardCharsets.UTF_8)); return null;}}, true) The parameter / / true means whether to expose the redis connection to the callback code. In most cases, you can set true. If you go further, you can see RedisConnection connToExpose = (exposeConnection? ConnToUse: createRedisConnectionProxy (connToUse)); if false, the proxy} subscriber of the redis connection will be created

Subscribers will have a little more content because they involve connections, threads, etc.

@ Resource private RedisTemplate redisTemplate; public void subscribe () {redisTemplate.execute (new RedisCallback () {@ Override public Object doInRedis (RedisConnection connection) throws DataAccessException {/ / I define a global ConcurrentHashMap to store the connection because the subsequent unsubscribing thread will use the same connection map.put ("connection", connection) as the subscribing thread. / / subscribe subscribing by channel this method blocks the thread and only unsubscribes will release the thread connection.subscribe (new MessageListener () {@ Override public void onMessage (Message message, byte [] pattern) {log.info ("received message") System.out.println (new String (message.getBody ();}}, "channelOne" .getBytes (StandardCharsets.UTF_8), "channelTwo" .getBytes (StandardCharsets.UTF_8)) / / subscribing to pSubscribe in mode will release the thread / / connection.pSubscribe only if you unsubscribe (new MessageListener () {/ / @ Override// public void onMessage (Message message, byte [] pattern) {/ / System.out.println (new String (message.getBody () / /} / /}, "patternOne" .getBytes (StandardCharsets.UTF_8), "patternOne" .getBytes (StandardCharsets.UTF_8); return null;}}, true);}

How to unsubscribe? Get the connection from the map just now

RedisConnection the = map.get ("connection"); Subscription subscription = the.getSubscription (); subscription.unsubscribe (); message listening container

The subscription above is a low-level subscription, because the connection causes the current thread to block when the subscribe is called, which requires connection and thread management for each listener, so spring provides the RedisMessageListenerContainer class to help us with this work.

As the name implies, RedisMessageListenerContainer is a message listening container.

Please refer to the official documentation for details.

How to realize

@ Configurationpublic class DefaultMessageListenerContainerConfig {@ Bean public RedisMessageListenerContainer container (RedisConnectionFactory factory) {RedisMessageListenerContainer container = new RedisMessageListenerContainer (); container.setConnectionFactory (factory); / / We officially recommend that we use a custom thread pool or use TaskExecutor container.setTaskExecutor (executor ()) Container.addMessageListener (new MessageListener () {@ Override public void onMessage (Message message, byte [] pattern) {System.out.println (Thread.currentThread (). GetName () + ":" + new String (message.getBody ());}}, new ChannelTopic ("message")); return container } @ Bean public TaskExecutor executor () {ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor (); executor.setCorePoolSize (Runtime.getRuntime (). AvailableProcessors ()); executor.setMaxPoolSize (Runtime.getRuntime (). AvailableProcessors () * 2); executor.setQueueCapacity (100); executor.initialize (); return executor;}}

At this point, when we use publish channel message on the redis command line, our spring program can subscribe to messages.

Again, MessageListenerAdapter.

We can wrap it through the MessageListenerAdapter message receiver, who does not have any coupling with the redis.

The official documentation gives spring the traditional xml configuration. Here is the code based on the configuration configuration.

Public interface MessageDelegate {void handleMessage (String message);} public class DefaultMessageDelegate implements MessageDelegate {@ Override public void handleMessage (String message) {System.out.println (message);} @ Configurationpublic class MessageListenerContainerConfig {@ Autowired private DefaultMessageDelegate defaultMessageDelegate; @ Bean public RedisMessageListenerContainer container (RedisConnectionFactory factory, MessageListenerAdapter messageListenerAdapter) {RedisMessageListenerContainer container = new RedisMessageListenerContainer (); container.setConnectionFactory (factory) Container.setTaskExecutor (executor ()); Map

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

Development

Wechat

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

12
Report