Redis pub/sub Spring stringredistemplate

Source: Internet
Author: User

Redis Subscription Publishing

Project Name: smremind_new

@Service
public class Pubserviceimpl implements Pubservice {
@Resource (name= "Stringredistemplate")
Private Stringredistemplate stringredistemplate;

Private String channeltopic = "baojing";

/* Post a message to channel*/
public void Publisher (String message) {


Stringredistemplate.convertandsend (channeltopic, message);
}
}




Sub-side I'm using Java do Service (Spring) management

Project Name Redis-service_pubsub

<!--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>



To run the 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 Infinite loop, set the value of Atomicboolean exit to True

Atomicboolean is thread-protected

Terminates the loop when the value of exit is False


The wait () method of calling object in the loop causes the program to wait because the wait () method exits abnormally for whatever reason, so the loop condition is exit with a value of false

Redismessagelistenercontainer creating a managed pub/sub thread pool for spring

Close the thread pool at the end of the loop

Because object is a static variable, call the Wait () method with synchronized


Receiving message Classes

public class Subserviceimpl implements Subservice {


Private Logger log = Logger.getlogger (This.getclass ());


@Autowired
Private Channeltopic channeltopic;
@Autowired
Private Linkmandao Linkmandao;
Private String BJHM = "13201706118";



public void onMessage (Message message, byte[] pattern) {
Message for receiving messages
System.out.println (message.tostring () + "1111" + channeltopic.gettopic () + "" + Thread.CurrentThread (). Getn Ame ());
Log.info ("redis-service_pubsub|" + channeltopic.gettopic () + "|" + message);
Parse Receive message;
string[] arg = message.tostring (). Split ("\\|");
Caller number
String callingnum = arg[0];
Called number
String callednum = arg[1];
Time
String calltime = arg[2];
if (Callednum.equals (BJHM)) {
Called number equals configuration number, query database get send SMS Collection
Temporarily use my phone number as the test number
list<linkman> list = Linkmandao.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);//post method is set to no cache
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 ();


Returns the status code of the 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";
}


}






Pause Service Receive

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 Service
MainPcl.exit.set (FALSE);
Synchronized (MAINPCL.O) {
O.notify ();
};
}
}

Two receive message classes are actually the same, just when configured

<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 channel value configured is not the same.



Redis pub/sub Spring stringredistemplate

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.