redis publish and subscribe Java code implementation

In addition to being able to cache data, Redis also implements the pub / sub message communication mode: the sender (pub) sends messages, and the subscriber (sub) receives messages.

In order to implement the publish and subscribe mechanism of redis, first open the redis service; secondly, introduce the jar package required by redis, and add the following code in the pom.xml configuration file:


Because the subscription message channel needs to be triggered when tomcat is started, a listener listener needs to be created to implement redis subscription in the listener. The listener configured in web.xml is as follows:


I. subscription message (implemented by InitListener)

redis supports multi-channel subscription. A client can subscribe to multiple message channels at the same time. As shown in the following code, it has subscribed to 13 channels. Because the subscription mechanism is thread blocking, an additional thread needs to be opened for processing subscription messages and receiving messages.

public class InitListener implements ServletContextListener{
    private Logger logger = Logger.getLogger(InitListener.class);
    public void contextInitialized(ServletContextEvent sce) {"start-up tomcat");// Connect redis
        Map<String, String> proMap = PropertyReader.getProperties();
        final String url = proMap.get("");
        final Integer port = Integer.parseInt(proMap.get("redis.port"));
        final ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("classpath*:applicationContext.xml");
        final RedisSubListener redisSubListener = (RedisSubListener) classPathXmlApplicationContext.getBean("redisSubListener");
        // To prevent blocking tomcat Start, start thread execution
        new Thread(new Runnable(){  
            public void run(){  
                // Connect redis,Build monitoring
                Jedis jedis = null;
                    //Decode resource update notification,Screen selection reply,Screen selection stop reply,Plan initiation,Plan stop,Wheel cut start,Wheel cut stop,Plan start reply,Plan stop reply,Turning start reply,Rotation stop Recovery,Monitoring screen split status notification,Picture status notification
                    String[] channels = new String[] { "decodeResourceUpdateNtf", "tvSplitPlayRsp","tvSplitPlayStopRsp",
                            "planStartStatusNtf", "planStopStatusNtf", "pollStartStatusNtf", "pollStopStatusNtf",
                        jedis = new Jedis(url,port);
              "redis Pull subscription channel");
              "redis Subscription end");
                    }catch(JedisConnectionException e){
                        logger.error("Jedis Connection exception,Abnormal information :" + e);
                    }catch(IllegalStateException e){
                         logger.error("Jedis abnormal,Abnormal information :" + e);
                    try {
                    } catch (InterruptedException e) {
                    if(jedis != null){
                        jedis = null;

Finally, access the following configuration in the spring configuration file:

<!-- redis -->
     <bean id="redisMessageService" class="com.test.service.impl.RedisMessageServiceImpl" scope="singleton">
         <property name="webSocketService"><ref local="webSocketService" /></property>
         <property name="tvSplitStatusDao" ref="tvSplitStatusDao"></property>
     <bean id="redisSubListener" class="com.test.common.RedisSubListener" scope="singleton">
         <property name="redisMessageService"><ref local="redisMessageService" /></property>
RedisMessageServiceImpl is used to process received redis messages.

II. News release

public class RedisPublishUtil {
    private Logger logger = Logger.getLogger(RedisPublishUtil.class);
    public static Jedis pubJedis;
    private static Map<String, String> proMap = PropertyReader.getProperties();
    private static final String redisPort = proMap.get("redis.port");
    private static String url = proMap.get("");
    private static final int port = Integer.parseInt(redisPort);
    public void setPubJedis(Jedis jedis) {
        RedisPublishUtil.pubJedis = jedis;
    public Jedis getPubJedis() {
        if (pubJedis == null) {
        // Return object
        return pubJedis;
    public Jedis createJedisConnect(){
        // Connect redis"===Create connection jedis=====");
        try {
            pubJedis = new Jedis(url, port);
        } catch (JedisConnectionException e) {
            logger.error("Jedis Connection exception,Abnormal information :" + e.getMessage());
            try {
      "Initiate reconnection jedis");
            } catch (InterruptedException except) {
        // Return object
        return pubJedis;
    //Public publishing interface
    public void pubRedisMsg(String msgType,String msg){"redis Prepare to publish message content:" + msg);
        try {
            this.getPubJedis().publish(msgType, msg);

        } catch (JedisConnectionException e) {
            logger.error("redis Failed to publish message!", e);
  "Republish the message, channel="+msgType);
            pubRedisMsg(msgType, msg);

public class PropertyReader {

     private static Logger logger = Logger.getLogger(PropertyReader.class);
     * Get profile for database link
    public static Map<String,String> getProperties(){"read redis Profile start...");
         Properties prop = new Properties();     
         Map<String,String> proMap  = new HashMap<String,String>();
        try {
             //Read property file
            InputStream in= PropertyReader.class.getClassLoader().getResourceAsStream("");  
            prop.load(in);     ///Load property list
            Iterator<String> it=prop.stringPropertyNames().iterator();
                proMap.put(key, prop.getProperty(key));
  "read redis Profile success...");
        } catch (Exception e) {
            logger.error("read redis Configuration file exception!", e);
        return proMap;

Tags: Java Redis Jedis xml Tomcat

Posted on Sun, 01 Dec 2019 14:47:53 -0800 by rortelli