Spring MVC Data redis-pub/sub (with Web project source code)

Source: Internet
Author: User

I. Release and subscription mechanisms

When a client sends a message to a subscriber via the PUBLISH command, we call the client Publisher.

When a client uses the SUBSCRIBE or Psubscribe command to receive information, we call the client the Subscriber (Subscriber).

To understand the relationship between a decoupled publisher (publisher) and a Subscriber (subscriber), Redis uses the channel as an intermediary for both-the publisher publishes the information directly to the channel, and the channel is responsible for sending the information to the appropriate subscribers. There is no correlation between the publisher and the Subscriber, and there is no known

Note: The pub sub feature of Redis (perhaps temporarily) does not support persistence, meaning that the message is lost in the pipeline, and the message is removed from the pipeline when the message is received by the subscriber side. Therefore, if the accuracy of the message is higher or there is a need for persistence, Redis is not so appropriate, expecting later versions to join the persistence feature.

Second, the role of Pub/sub

In fact, from the pub/sub mechanism, it is more like a broadcast system, multiple subscriber can subscribe to multiple channel, more than one publisher can publish messages to multiple channel. can be so simple to understand:

Subscriber: Radio (only this radio can receive multiple channels and is displayed as a queue)

Publisher: Radio (radio can be used to send messages in different FM channels)

CHANNEL: FM channel of different frequency

So according to this understanding, then I think there are several uses are more desirable:

1. One publisher, multiple subscriber:

As shown, it can be either a message queue or a message pipeline.

Main applications: Notifications, announcements.

2. Multiple publisher, one subscriber:

The pubsub can be made into a separate HTTP interface, where each application sends a message to the channel as publisher, and the Subscriber receives the message and executes the appropriate business logic, such as writing the database, displaying it, and so on.

Main applications: Leaderboard, poll, count.

3. Multiple publisher, multiple subscriber

The figure is not on, so the name Incredibles, is can be sent to different channel messages, by different subscriber receive.

Main applications: Group chat, chat.

You can refer to the Open source project RETWISJ of the Spring Data Redis home page.

GitHub Address: HTTPS://GITHUB.COM/SPRING-PROJECTS/SPRING-DATA-KEYVALUE-EXAMPLES/TREE/MASTER/RETWISJ

From the above several usages, according to different restrictions, limit publisher, subscriber and channel number, can achieve different functions, in fact, can fully understand pub/sub as socket programming, with the socket can also achieve the above functions, But Redis provides the appropriate package and the underlying implementation, regardless of security, robustness and other aspects of good performance, as well as some future development, the individual think Redis is a good choice.

Three, demo Demo:

Because of my previous blog introduction to spring Data Redis and the project Demo,redistemplate and serializer, the basic configuration and use of spring data Redis has been demonstrated, so this is only affixed to the pub/ Sub of the important Code, readers can read the previous blog or download source.

Pub/sub configuration (XMl):

 1 <!--SDR pub/sub configuration--2 <!--Subserviceimpl is the class that implements the MessageListener interface, the OnMessage method is defined in the MessageListener interface, that is, the receiving The method of the message, the OnMessage method is automatically called whenever there is a message in the channel, and 3 <bean id= "MessageListener" class= " Com.chr.service.impl.SubServiceImpl "> 4 </bean> 5 6 <!--can have multiple messagelistener, each messagelistener must be Register to Redismessagelistenercontainer, readers can refer to API documentation--7 <bean id= "Messagecontainer" 8 class= "Org.springframew Ork.data.redis.listener.RedisMessageListenerContainer "9 destroy-method=" destroy ">10 <property name= "ConnectionFactory" ref= "ConnectionFactory"/>11 <!--<property name= "Taskexecutor" > <bean class= "or G.springframework.scheduling.concurrent.threadpooltaskscheduler "> <property name=" poolSize "value=" 3 "> </property> </bean> </property>13 Here you can define Executor, see java.util.concurrent.executor-->14 <pro    Perty name= "Messagelisteners" >15 <map>16             <entry key-ref= "MessageListener" >17 <ref bean= "Channeltopic"/>18 </entry>19 </map>20 </property>21 </bean>22 <!--channel settings -->24 <bean id= "Channeltopic" class= "Org.springframework.data.redis.listener.ChannelTopic" >25 <con Structor-arg value= "User:topic"/>26 </bean>

You can see in the code that the Subserviceimpl implementation class is manually registered in the configuration file, which can confuse the code and cause problems, such as the need to use annotations to automatically inject Rankservice, but because of the spring configuration, The precedence of XML is greater than annotation, so rankservice in Subserviceimpl cannot be @autowired.

There are two ways to solve this problem:

1. In the configuration file (before the Messagelisener Bean), add:

<!--scanner--    <context:component-scan base-package= "Com.songod.service"/>

Spring will then scan annotation, create rankservice beans, and then inject Messagelisener.

2. In the Messagecontainer bean, only connectionfactory are injected, not messagelisener and channeltopic. Then manually injected in the controller, call Addmessagelistener (MessageListener Listener, Topic Topic) method manual injection, but note can only be injected once, you can set the flag judgment.

Pubserviceimpl:
1 @Service 2 public class Pubserviceimpl implements Pubservice {3     @Resource (name= "Stringredistemplate") 4     Private  stringredistemplate stringredistemplate; 5      6     private String channeltopic = "User:topic"; 7      8     /* Publish message to channel*/9 public     void Publisher (String message) {         Stringredistemplate.convertandsend ( Channeltopic, message);     }12}

I use stringredistemplate here, readers can use Redistemplate to set other serialization methods, you can see my previous blog.

Subserviceimpl:
public class Subserviceimpl implements Subservice {    @Autowired    private channeltopic channeltopic;    Private Messagelist messagelist = new Messagelist ();    public void onMessage (Message message, byte[] pattern) {        System.out.println (message.tostring () + "  " + Channeltopic.gettopic ());        Messagelist.add (Message.tostring ());    }    Public Messagelist getmessagelist () {        return messagelist;    }}

It is primarily the OnMessage method, which can be processed in this method by passing the message into other business logic.

FourDemo Run:Publish:

Subscrib:

V. Project source code:

Redis-web-pubsub

Spring MVC Data redis-pub/sub (with Web project source code)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.