一·引入依賴
<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);