1. 程式人生 > >redisTemplate 實現訂閱與釋出

redisTemplate 實現訂閱與釋出

package testMaven2;

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.core.RedisTemplate;

public class RedisMessageListener implements MessageListener {

	@Autowired
	private RedisTemplate<String, Object> redisTemplate;
	
	/**
	 * @return the redisTemplate
	 */
	public RedisTemplate<String, Object> getRedisTemplate() {
		return redisTemplate;
	}

	/**
	 * @param redisTemplate the redisTemplate to set
	 */
	public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
		this.redisTemplate = redisTemplate;
	}

	@Override
	public void onMessage(Message message, byte[] pattern) {
		byte[] body = message.getBody();
		String msgBody = (String) getRedisTemplate().getValueSerializer().deserialize(body);
		System.out.println(msgBody);
		byte[] channel = message.getChannel();
		String msgChannel = (String) getRedisTemplate().getValueSerializer().deserialize(channel);
		System.out.println(msgChannel);
		String msgPattern = new String(pattern);
		System.out.println(msgPattern);
	}

	
}
<?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:p="http://www.springframework.org/schema/p"  
	   xmlns:context="http://www.springframework.org/schema/context"   
	   xmlns:tx="http://www.springframework.org/schema/tx"
	   xsi:schemaLocation="http://www.springframework.org/schema/beans 
					http://www.springframework.org/schema/beans/spring-beans-4.3.xsd 
					http://www.springframework.org/schema/context 
					http://www.springframework.org/schema/context/spring-context-4.0.xsd 
					http://www.springframework.org/schema/aop 
					http://www.springframework.org/schema/aop/spring-aop-4.0.xsd 
					http://www.springframework.org/schema/tx 
					http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">

	<!-- 配置JedisPoolConfig -->
	<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
		 <!-- 最大連線數 -->
        <property name="maxTotal" value="30" />
        <!-- 最大空閒連線數 -->
        <property name="maxIdle" value="10" />
        <!-- 每次釋放連線的最大數目 -->
        <property name="numTestsPerEvictionRun" value="1024" />
        <!-- 釋放連線的掃描間隔(毫秒) -->
        <property name="timeBetweenEvictionRunsMillis" value="30000" />
        <!-- 連線最小空閒時間 -->
        <property name="minEvictableIdleTimeMillis" value="1800000" />
        <!-- 連線空閒多久後釋放, 當空閒時間>該值 且 空閒連線>最大空閒連線數 時直接釋放 -->
        <property name="softMinEvictableIdleTimeMillis" value="10000" />
        <!-- 最大等待毫秒數,小於零:阻塞不確定的時間,預設-1 -->
        <property name="maxWaitMillis" value="1500" />
        <!-- 在獲取連線的時候檢查有效性, 預設false -->
        <property name="testOnBorrow" value="true" />
        <!-- 在空閒時檢查有效性, 預設false -->
        <property name="testWhileIdle" value="true" />
        <!-- 連線耗盡時是否阻塞, false報異常,true阻塞直到超時, 預設true -->
        <property name="blockWhenExhausted" value="false" />
	</bean>

	<!-- 配置JedisConnectionFactory -->
	<bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
		<property name="hostName" value="localhost" />
		<property name="port" value="6379" />
		<property name="poolConfig" ref="poolConfig" />
	</bean>

	<!-- 配置Spring RedisTemplate -->
	<bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" id="jdkSerializationRedisSerializer" />
	<bean class="org.springframework.data.redis.serializer.StringRedisSerializer" id="stringRedisSerializer" />
	<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
		<property name="connectionFactory" ref="jedisConnectionFactory"/>
		<property name="defaultSerializer" ref="stringRedisSerializer"/>
		<property name="keySerializer" ref="stringRedisSerializer"/>
		<!-- <property name="valueSerializer" ref="jdkSerializationRedisSerializer"/> -->
		<property name="valueSerializer" ref="stringRedisSerializer"/>
	</bean>	
	
	<!-- 定義監聽類 -->
	<bean id="redisMessageListener" class="testMaven2.RedisMessageListener">
		<property name="redisTemplate" ref="redisTemplate"/>
	</bean>
	
	<!-- 定義監聽容器 -->
	<bean id="redisMessageListenerContainer" class="org.springframework.data.redis.listener.RedisMessageListenerContainer" destroy-method="destroy">
		<property name="connectionFactory" ref="jedisConnectionFactory"/>
		<!-- 任務執行器 -->
		<property name="taskExecutor">
			<bean class="org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler">
				<property name="poolSize" value="10"/>
			</bean>
		</property>
		<!-- 訊息監聽器 -->
		<property name="messageListeners">
			<map>
				<entry key-ref="redisMessageListener">
					<list>
						<!-- <bean class="org.springframework.data.redis.listener.ChannelTopic">
							<constructor-arg value="chat1" />
						</bean>
						<bean class="org.springframework.data.redis.listener.ChannelTopic">
							<constructor-arg value="chat2" />
						</bean> -->
						<bean class="org.springframework.data.redis.listener.PatternTopic">
							<constructor-arg value="chat*" />
						</bean>
					</list>
				</entry>
			</map>
		</property>
	</bean>
</beans>
package testMaven2;

import java.io.UnsupportedEncodingException;
import java.text.ParseException;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:config/spring-redis.xml" })
public class CodeTest1 {
	@Autowired
	ApplicationContext applicationContext;
	@Autowired
	RedisTemplate<String, Object> redisTemplate;

	@SuppressWarnings("unchecked")
	@Test
	public void test() throws UnsupportedEncodingException, ParseException {
		redisTemplate = applicationContext.getBean(RedisTemplate.class);
		String channel = "chat1";
		String msg = "hello";
		redisTemplate.convertAndSend(channel, msg);
		String channel1 = "chat2";
		String msg1 = "world";
		redisTemplate.convertAndSend(channel1, msg1);
	}

}

最後輸出:

hello
chat1
chat*
world
chat2
chat*