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 redisTemplate;
	
	/**
	 * @return the redisTemplate
	 */
	public RedisTemplate getRedisTemplate() {
		return redisTemplate;
	}

	/**
	 * @param redisTemplate the redisTemplate to set
	 */
	public void setRedisTemplate(RedisTemplate 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);
	}

	
}



	
	
		 
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
	

	
	
		
		
		
	

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

你可能感兴趣的:(Redis)