The Redis server can implement a simple message "Publish/subscribe" service, the following is a description of the Spring-redis implementation
Spring-redis use Redismessagelistenercontainer for message monitoring, client programs need to implement their own messagelistener, and registered with the specified topic to Redismessagelistenercontainer,
In this way, if there is a message on the specified topic, Redismessagelistenercontainer will notify the MessageListener.
The following is the configuration of Spring-redis in the spring configuration file:
<bean id= "Jedispoolconfig" class= "Redis.clients.jedis.JedisPoolConfig" > <property name= "Maxtotal" "></property> <property name=" Maxidle "value=" ></property> <property name= "
Minidle "value=" ></property> <property name= "Maxwaitmillis" value= "to" ></property> <property name= "Testonborrow" value= "true" ></property> <property name= "Testonreturn" value= E "></property> </bean> <bean id=" jedisconnectionfactory "class=" Org.springframework.data.redis. Connection.jedis.JedisConnectionFactory "> <property name=" hostName "value=" 127.0.0.1 "/> <prope
Rty name= "Port" value= "6379"/> <property name= "poolconfig" ref= "Jedispoolconfig" ></property> <property name= "Timeout" value= "5000" ></property> <property name= "Usepool" value= "true" ></p Roperty> </bean> <!--redis Template--> <bean id= "Redistemplate" class= Mplate "> <property name=" connectionfactory "ref=" jedisconnectionfactory "/> </bean> <bea n id= "Redismsglistener" class= "My.test.listener.RedisMessageListener" > <property name= "redistemplate" ref= "R" Edistemplate "/> </bean>
In the example above, the last two bean configurations are the key to implementing the Publish/Subscribe service. Redismessagelistener is written by himself to achieve the Org.springframework.data.redis.connection.MessageListener business class,
and to "topic123" This topic register to Redismessagelistenercontainer. Redismessagelistenercontainer is responsible for notifying MessageListener when the message arrives. Here is the code for Redismessagelistener:
Class Redismessagelistener implements MessageListener {
@Autowired
redistemplate redistemplate; Redisserializer serializer
@Override
void onMessage (Message message, byte[] pattern) {
serializer = Redistemplate.getvalueserializer ()
String messagestr = serializer.deserialize (message.body)
println (" Message Received: "+ Messagestr)
}}"
In this way, when the application starts, the Subscriber (Subscriber) of the message is registered. When you use a simple program that simulates publisher and publishes a message to the specified topic, Redismessagelistener can receive the message,
Spring-redis's writing is this:
Redistemplate.convertandsend ("topic123", "Hello there!")