Spring-redis:实现发布/订阅(亲测有效,欢迎提问)

原理:Spring与redis整合后,配置的监听器会对项目进行监听,每当调用RedisTemplate这个类的convertAndSend(java.lang.String channel, java.lang.Object message)方法,像指定的频道(在配置文件之中)发送一条消息,该消息就会被监听器监听到,进而实现发布订阅功能。

一、导入maven依赖

spring集成redis需要导入的maven依赖有两个,如下:

        
            org.springframework.data
            spring-data-redis
            1.6.2.RELEASE
        
        
            redis.clients
            jedis
            2.8.2
        

二、新建redis配置文件,配置redis服务器相关信息

文件名为:redis.properties

redis.host=localhost
redis.port=6379
redis.password=
redis.database=0
redis.timeout=1000
#session valid time
redis.maxInactiveIntervalInSeconds=1800

#redis pool config
redis.pool.maxTotal=300
redis.pool.maxIdle=5
redis.pool.minIdle=1
redis.pool.maxWaitMillis=6000
redis.pool.testWhileIdle=true
redis.testOnBorrow=true

三、新建redis配置文件redis-context.xml文件,注册redis相关配置信息




    
    

    

    
    

    
    

    
        
        
        
    

    
    
        
        
        
        
        
        
        
    
    
    
        
        
        
        
        
    

    
    
    
    
    

    
    
    
    
        
        
        
    

    
    
        
        
        
    

四、spring-mvc.xml配置如下




    
    
    
    
    
    
    

    
    
        
        
        
    

    
    

五、web.xml配置如下(仅供参考,看实际情况配置)



  
  
    contextConfigLocation
    classpath:spring-mybatis.xml
  

  
  
    encodingFilter
    org.springframework.web.filter.CharacterEncodingFilter
    true
    
      encoding
      UTF-8
    
  
  
    encodingFilter
    /*
  

  
  
    org.springframework.web.context.ContextLoaderListener
  
  
  
    org.springframework.web.util.IntrospectorCleanupListener
  

  
  
    SpringMVC
    org.springframework.web.servlet.DispatcherServlet
    
      contextConfigLocation
      classpath:spring-mvc.xml
    
    1
    true
  
  
    SpringMVC
    
    /
  

  
    /index.jsp
  

六、新建一个发布信息的类:发布的消息不可以为null,否则redis在set消息时会报NullPointerException

package xin.shenwan.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

/**
 * @author 12450
 */
@Component
public class SendMessage {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 该方法调用redisTemplate发布信息,
     * @param channel 发布信息的频道名称
     * @param message 要发布的信息
     */
    public synchronized void sendMessage(String channel, String message) {
        redisTemplate.convertAndSend(channel, message);
    }


}

七、新建用于监听redis发布并获取到发布信息的监听类(该类实现了redis监听接口)

这里需要注意:实际情况中采用哪一种序列化方式合适就选择哪一种,选择时配置文件中的相关配置也需要进行更改

package xin.shenwan.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import xin.shenwan.socket.RsSocket;

/**
 * @author 12450
 */
public class DataSyncEventListener implements MessageListener {
    @Autowired
    private RedisSerializer stringRedisSerializer;
    @Autowired
    private JdkSerializationRedisSerializer jdkSerializationRedisSerializer;

    /**
     * 需要重写MessageListener的方法
     *
     * @param message
     * @param bytes
     */
    @Override
    public void onMessage(Message message, byte[] bytes) {
        String channel = stringRedisSerializer.deserialize(message.getChannel());
        Object object = stringRedisSerializer.deserialize(message.getBody());
        //采用jdk方式进行序列化
        /*Object channel = jdkSerializationRedisSerializer.deserialize(message.getChannel());
        Object object = jdkSerializationRedisSerializer.deserialize(message.getBody());*/
        System.out.println("channel is :" + channel);
        //向客户端发送的信息
        String messageToUser = object.toString();
        System.out.println("message is :" + messageToUser);
    }
}

八、测试类

package xin.shenwan.controller;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import xin.shenwan.redis.SendMessage;

@Controller
@RequestMapping(value = "/test")
public class RedisTest {
    @Autowired
    SendMessage sendMessage;

    @RequestMapping(value = "/sendMsg")
    public void redis() {
        for (int i = 0; i < 10; i++) {
            sendMessage.sendMessage("channel1.0", "第" + i + "次发送信息");
        }
    }
}

启动项目访问链接,注意看控制台输出:

只是很基础的入门总结,欢迎各位大神提出改进意见。

你可能感兴趣的:(redis,spring)