一·引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
二·配置文件
spring:
redis:
host: redis
port: 6379
timeout: 3000
password: ""
三·开发
1·redis发布订阅配置类 RedisSubListenerConfig
listenerAdapter 构造适配器 以及 指定 listener 接收消息的方法
RedisMessageListenerContainer 对 topic 添加 监听适配器
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/**
* 说明:
*
* @version V1.0
* @since 2019.4.25
*/
@Configuration
public class RedisSubListenerConfig {
@Autowired
private JedisConnectionFactory jedisConnectionFactory;
@Bean
RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory, MessageListenerAdapter listenerAdapter) {
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
container.addMessageListener(listenerAdapter, new PatternTopic(VideoConstant.TOPIC_VIDEO));
return container;
}
@Bean
MessageListenerAdapter listenerAdapter(HandlerService handlerService ) {
return new MessageListenerAdapter(handlerService , "receive");
}
@Bean
StringRedisTemplate template(RedisConnectionFactory connectionFactory) {
return new StringRedisTemplate(connectionFactory);
}
@Bean
public RedisTemplate<String, String> redisTemplateString() {
RedisTemplate<String, String> template = new RedisTemplate<>();
template.setConnectionFactory(jedisConnectionFactory);
template.setKeySerializer(new StringRedisSerializer());
template.setHashKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new StringRedisSerializer());
return template;
}
}
2·HandlerService 自己编写实现类 实现接收到消息 对消息的处理逻辑
public interface HandlerService {
/**
* 接收消息
*/
void receive(String map);
}
3·发送消息
@Autowired
private RedisTemplate<String, String> redisTemplateString;
redisTemplate.convertAndSend(topic, msg);