SSM項目整合redis的訂閱發佈

redis的下載安裝

參考地址:
http://www.runoob.com/redis/redis-install.html
如上面無法下載可通過下面地址下載:
鏈接:https://pan.baidu.com/s/1aO8TJr4al2ZDeLul-xwWQA
提取碼:brym

整合redis

僅僅簡單整合redis的訂閱發佈功能,不使用緩存功能
首先java操作Redis的方式有兩種(據我所知)
1. 使用Spring Data Redis操作Redis
2. 使用Jedis 操作redis(參考地址:https://blog.csdn.net/lovelichao12/article/details/75333035/)
我們這裏採用第一種,第二種給個參考地址感興趣的可以看看

個人理解
既然是實現訂閱和發佈,那就有消息的發送方和接收方。
發送方 發送消息
1.通過JedisConnection的Pub/Sub相關的方法來向Redis服務發佈消息
2.RedisTemplate的convertAndSend方法(使用的)
接收方 包括監聽消息並輸出,需要實現消息監聽類並在xml中註冊這個類
兩種方式實現監聽類
- 一種是實現org.springframework.data.redis.connection.MessageListener接口,實現onMessage方法(使用的)
- 使用自己定義的類,方法名稱自己定義
兩種方式來實現消息監聽容器的聲明
- 一種是通過Redis的命名空間
- 一種是定義Bean (使用的)
參考博客 http://blog.51cto.com/aiilive/1627478 來理解這兩種方式
maven引入Redis
pom.xml

<!--redis 訂閱發佈 -->
<dependency>
	<groupId>org.springframework.data</groupId>
	<artifactId>spring-data-redis</artifactId>
	<version>1.6.4.RELEASE</version>
</dependency>
<dependency>
	<groupId>redis.clients</groupId>
	<artifactId>jedis</artifactId>
	<version>2.9.0</version>
</dependency>

在resource資源包下建立redis文件下建立redis.properties

# Redis settings
redis.host=127.0.0.1
redis.port=6379
redis.timeOut=10000
redis.usePool=true
# redis.pass=

redis.maxIdle=300  
redis.maxTotal=1024  
redis.maxWaitMillis=10000  
redis.testOnBorrow=true  
redis.maxActive=3000
redis.maxWait=10000

# channel
redis.test.channel1=channel1
redis.test.channel2=channel2

並在spring文件夾下建立redis.xml,其中com.sys.service.impl.RedisTestMessageListener在後面會創建

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:cache="http://www.springframework.org/schema/cache"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	   		http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
			http://www.springframework.org/schema/tx
			http://www.springframework.org/schema/tx/spring-tx.xsd
			http://www.springframework.org/schema/context
	   		http://www.springframework.org/schema/context/spring-context-4.1.xsd
			http://www.springframework.org/schema/mvc
			http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
			http://www.springframework.org/schema/aop 
			http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
			http://www.springframework.org/schema/cache
			http://www.springframework.org/schema/cache/spring-cache.xsd">

    <!-- 加載redis文件  --> 
    <context:property-placeholder location="classpath:redis/redis.properties" />

    <!-- redis 整合 -->
    <!-- jedis pool配置 --> 
    <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
        <property name="maxTotal" value="${redis.maxActive}"/>
        <property name="maxIdle" value="${redis.maxIdle}"/>
        <property name="maxWaitMillis" value="${redis.maxWait}"/>
        <property name="testOnBorrow" value="${redis.testOnBorrow}"/>
    </bean>
    <!-- spring data redis -->  
    <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">  
        <property name="poolConfig" ref="jedisPoolConfig"></property>
		<property name="hostName" value="${redis.host}"></property>
		<property name="port" value="${redis.port}"></property>
		<property name="timeout" value="${redis.timeOut}"></property>
	    <property name="usePool" value="${redis.usePool}"></property>
    </bean>  
    
    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">  
        <property name="connectionFactory" ref="jedisConnectionFactory"/> 
        <property name="keySerializer">
			<bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />
		</property>
		<property name="hashKeySerializer"> 
            <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />
        </property> 
		<property name="valueSerializer">
			<bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />
		</property> 
    </bean>
        
    <!-- 消息接受類 -->
    <bean id="redisTestMessageListener" class="com.sys.service.impl.RedisTestMessageListener"></bean>  
    <bean id="redisContainer" class="org.springframework.data.redis.listener.RedisMessageListenerContainer">
        <property name="connectionFactory" ref="jedisConnectionFactory" />
        <property name="taskExecutor"> 
            <bean class="org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler">  
                <property name="poolSize" value="2"></property>  
            </bean>  
        </property>
        <property name="messageListeners">
            <map>
                <entry key-ref="redisTestMessageListener">
                    <list>
                        <!-- 普通訂閱,訂閱具體的頻道   -->
                        <bean class="org.springframework.data.redis.listener.ChannelTopic">
                            <constructor-arg value="${redis.test.channel1}" />
                        </bean>
                        <bean class="org.springframework.data.redis.listener.ChannelTopic">
                            <constructor-arg value="${redis.test.channel2}" />
                        </bean>                       
                    </list>
                </entry>
            </map>
        </property>
    </bean> 
<bean id="stringRedisSerializer" class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
</beans>

web.xml引入redis.xml的配置

	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:spring/redis.xml</param-value>
	</context-param>
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

到此配置已經完成
參考
Redis消息的發佈/訂閱 https://blog.csdn.net/m15732622413/article/details/78414891
java+redis+spring mvc實現發佈訂閱 https://blog.csdn.net/m0_37064092/article/details/54617297
redis 消息發佈訂閱與消息隊列 https://blog.csdn.net/jslcylcy/article/details/78201812

代碼測試

創建相應的controller service 發送消息

@Service("sendRedisService")
public class SendRedisServiceimpl implements SendRedisService {
	@Autowired
	public RedisTemplate<String, Object> redisTemplate;
	@Override
	public void sendMessage(String channel, String message) {
		System.out.println("開始向"+channel+"發佈消息"+ message);
		redisTemplate.convertAndSend(channel, message);
		System.out.println("發佈成功!");
	}

創建 redis.xml中定義的 監聽類

@Component
public class RedisTestMessageListener implements MessageListener {
	@Resource
	public RedisTemplate<String, Object> redisTemplate;

//redisTemplate 注入失敗 使用這種方法 會空指針
/*	@Override
	public void onMessage(Message message, byte[] pattern) {
		String topic = (String) redisTemplate.getStringSerializer().deserialize(message.getChannel());
		Object body = redisTemplate.getValueSerializer().deserialize(message.getBody());
		String msg = String.valueOf(body);
		System.out.println(topic);
		System.out.println("接受消息:" + msg);
	}
	*/
	//使用這種方法 會出現中文亂碼
	@Override
	public void onMessage(Message message, byte[] pattern) {
		System.out.println("channel:" + new String(message.getChannel())
				+ ",message:" + new String(message.getBody()));
	}

}

此時請求發送消息,會輸出信息(當然你的redis是啓動的)
輸入 redis-cli.exe
訂閱channel1 subscribe channel1
同樣可以監聽到消息
在這裏插入圖片描述

發佈消息
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章