Redis pub/sub Spring StringRedisTemplate, redispubsub

Source: Internet
Author: User

Redis pub/sub Spring StringRedisTemplate, redispubsub

Redis subscription and release

Project name: SmRemind_NEW

@ Service
Public class PubServiceImpl implements PubService {
@ Resource (name = "stringRedisTemplate ")
Private StringRedisTemplate stringRedisTemplate;

Private String channelTopic = "Baojing ";

/* Publish a message to the Channel */
Public void Publisher (String message ){


StringRedisTemplate. convertAndSend (channelTopic, message );
}
}




Sub client I am using java for service (Spring) Management

Redis-service_pubsub project name

<! -- SDR Pub/Sub configuration -->
<Bean id = "topicMessageListener" class = "com. chr. service. impl. SubServiceImpl">

</Bean>
<Bean id = "topicMessageListener_stop" class = "com. chr. service. impl. stopServiceImpl"> </bean>
<Bean id = "topicContainer"
Class = "org. springframework. data. redis. listener. RedisMessageListenerContainer"
Destroy-method = "destroy">
<Property name = "connectionFactory" ref = "connectionFactory"/>
<Property name = "messageListeners">
<Map>
<Entry key-ref = "topicMessageListener">
<! -- <Bean class = "org. springframework. data. redis. listener. ChannelTopic">
<Constructor-arg value = "user: topic"/> </bean> -->
<Ref bean = "channelTopic"/>
</Entry>
<Entry key-ref = "topicMessageListener_stop">
<! -- <Bean class = "org. springframework. data. redis. listener. ChannelTopic">
<Constructor-arg value = "user: topic"/> </bean> -->
<Ref bean = "channelTopics"/>
</Entry>
</Map>
</Property>
</Bean>


<Bean id = "channelTopic" class = "org. springframework. data. redis. listener. ChannelTopic">
<Constructor-arg value = "Baojing"/>
</Bean>
<Bean id = "channelTopics" class = "org. springframework. data. redis. listener. ChannelTopic">
<Constructor-arg value = "tuichu"/>
</Bean>



Main class:

Public class MainPcl {


Public static Object o = new Object ();
Public static AtomicBoolean exit = new AtomicBoolean ();


Public static void main (String [] args) throws InterruptedException {
ApplicationContext context = new ClassPathXmlApplicationContext ("spring-context.xml ");
RedisMessageListenerContainer r = (RedisMessageListenerContainer) context. getBean ("topicContainer ");
Exit. set (true );
While (exit. get ()){
Synchronized (o ){
O. wait ();
};
}
R. stop ();
}
}

Write an infinite loop. Set AtomicBoolean exit to true.

AtomicBoolean is thread-protected

Terminate the loop when the exit value is false.


The wait () method of the object is called in the loop to wait for the program. Because the wait () method will exit abnormally for whatever reason, the loop condition is that the exit value is false.

RedisMessageListenerContainer creates a managed pub/sub thread pool for spring

Close the thread pool at the end of the loop

Because the object is a static variable, synchronized is used to call the wait () method.


Receive message class

Public class SubServiceImpl implements SubService {


Private Logger log = Logger. getLogger (this. getClass ());


@ Autowired
Private ChannelTopic channelTopic;
@ Autowired
Private linkmanDao;
Private String bjhm = "13201706118 ";



Public void onMessage (Message message, byte [] pattern ){
// The Message is used to receive messages.
// System. out. println (message. toString () + "1111" + channelTopic. getTopic () + "" + Thread. currentThread (). getName ());
Log.info ("redis-service_pubsub |" + channelTopic. getTopic () + "|" + message );
// Parse and receive messages;
String [] arg = message. toString (). split ("\\| ");
// Caller ID
String callingnum = arg [0];
// Called Number
String callednum = arg [1];
// Time
String calltime = arg [2];
If (callednum. equals (bjhm )){
// The called number is equal to the configured number. query the database to obtain the set of sent SMS messages.
// Temporarily use my mobile phone number as the test number
List <linkman> list = linkmanao. getlinkman_Userid ("13259781605 ");
For (linkman l: list ){

}
}


}


Public String send (String smsUrl, String message, String phonenum ){
String sendurl = String. format (smsUrl, phonenum );
Log.info ("redis-service_pubsub | send |" + phonenum + "| success | url:" + sendurl + "| message:" + message );
// If (true ){
// Return "OK ";
//}


Try {
URL url = new URL (sendurl );
HttpURLConnection httpCon = (HttpURLConnection) url. openConnection ();
HttpCon. setRequestProperty ("Content-type", "application/x-www-form-urlencoded; charset = UTF-8 ");
HttpCon. setRequestMethod ("POST ");
HttpCon. setUseCaches (false); // the POST method is set to cache-free.
HttpCon. setDoOutput (true );
HttpCon. setConnectTimeout (5000 );
HttpCon. setReadTimeout (5000 );


// The POST method writes the content as a stream
OutputStreamWriter out = new OutputStreamWriter (httpCon. getOutputStream (), "UTF-8 ");
Out. write (message );
Out. flush ();
Out. close ();


// Return the status code of request Completion
Int httpcode = httpCon. getResponseCode ();
If (httpcode = 204 ){
Return "OK ";
} Else {
Return "exp ";
}


} Catch (Exception e ){
Log. error ("redis-service_pubsub | send |" + phonenum + "| error | url:" + sendurl + "| message:" + message, e );
Return "exp ";
}


}






Suspend service reception

Public class stopServiceImpl implements SubService {


Private Logger log = Logger. getLogger (this. getClass ());
@ Autowired
Private ChannelTopic channelTopics;


Public void onMessage (Message message, byte [] pattern ){
Log.info ("redis-service_pubsub |" + channelTopics. getTopic () + "|" + message );
// Close the service
MainPcl. exit. set (false );
Synchronized (MainPcl. o ){
O. Policy ();
};
}
}

The two message receiving classes are actually the same, only when configuring

<Bean id = "channelTopic" class = "org. springframework. data. redis. listener. ChannelTopic">
<Constructor-arg value = "Baojing"/>
</Bean>
<Bean id = "channelTopics" class = "org. springframework. data. redis. listener. ChannelTopic">
<Constructor-arg value = "tuichu"/>
</Bean>


The value of the configured channel is different.



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.