Springboot 集成redis,來寫一個發佈訂閱吧
1.Springboot版本:2.X
2.pom依賴
首先呢,在pom文件裏,加入下面依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
3.配置文件
配置文件裏是使用redis需要的基本配置,沒有密碼是因爲本機的redis沒有設置密碼,使用起來方便。
spring:
redis:
database: 0 # Redis數據庫索引(默認爲0)
host: localhost # Redis服務器地址
port: 6379 # Redis服務器連接端口
password: # Redis服務器連接密碼(默認爲空)
timeout: 1000 # 連接超時時間(毫秒)
jedis:
pool:
max-active:
max-active: -1 # 連接池最大連接數(使用負值表示沒有限制)
max-wait: -1 # 連接池最大阻塞等待時間(使用負值表示沒有限制)
max-idle: 8 # 連接池中的最大空閒連接
min-idle: 0 # 連接池中的最小空閒連接
4.嘗試方便又好用的RedisTemplate
來初始化一個RedisTemplate吧
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
//使用StringRedisSerializer來序列化和反序列化redis的value值
redisTemplate.setKeySerializer(new StringRedisSerializer());
//使用Jackson2JsonRedisSerializer來序列化和反序列化redis的value值
Jackson2JsonRedisSerializer<Object> redisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
ObjectMapper mapper = new ObjectMapper();
mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
redisSerializer.setObjectMapper(mapper);
redisTemplate.setValueSerializer(redisSerializer);
return redisTemplate;
}
RedisTemplate整合了調用redis的api,使用起來十分方便,RedisTemplate定義了不同的操作對象來操作不同的數據結構
private @Nullable ValueOperations<K, V> valueOps;
private @Nullable ListOperations<K, V> listOps;
private @Nullable SetOperations<K, V> setOps;
private @Nullable ZSetOperations<K, V> zSetOps;
private @Nullable GeoOperations<K, V> geoOps;
private @Nullable HyperLogLogOperations<K, V> hllOps;
不過呢,像ValueOperations這些操作對象都用不到,這次體驗的是發佈訂閱功能喲。
5.發佈消息
@Slf4j
@RestController
public class PubController {
@Autowired
private RedisTemplate redisTemplate;
@GetMapping("/pub")
public void pub (String message){
log.info("eureka-client 發佈消息{}", message);
redisTemplate.convertAndSend("eureka-client", message);
}
}
這個類主要就是提供一個接口,然後在接口中調用redisTemplate的void convertAndSend(String channel, Object message)
方法。設置對應的頻道和消息內容。
6.訂閱消息
@Bean
RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
MessageListenerAdapter listenerAdapter) {
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
container.addMessageListener(listenerAdapter, new PatternTopic("eureka-client"));
return container;
}
通過注入上面的bean來決定訂閱哪個頻道,這裏訂閱了發佈消息的"eureka-client"頻道。
@Slf4j
@Component
public class RedisSubscriber extends MessageListenerAdapter {
@Autowired
private RedisTemplate redisTemplate;
@Override
public void onMessage(Message message, byte[] bytes) {
byte[] body = message.getBody();
byte[] channel = message.getChannel();
Object msg = redisTemplate.getStringSerializer().deserialize(body);
String topic = redisTemplate.getStringSerializer().deserialize(channel).toString();
log.info("監聽到topic爲" + topic + "的消息:" + msg.toString());
}
}
上面的類RedisSubscriber繼承了MessageListenerAdapter,重寫了接收到消息以後的邏輯,這裏就是將消息內容和
頻道打印了出來,使用@Component可以將這個類加入容器中。
7.測試
瀏覽器訪問http://localhost:2000/pub:
http://localhost:2000/pub?message=hh
日誌打印:
監聽到topic爲eureka-client的消息:“hh”
說明這個可以發佈訂閱可以正常使用。
再試一下發布的消息爲一個bean對象:
實體Bean:
@Getter
@Setter
public class Employee {
private String name;
private String address;
public Employee(String name, String address) {
this.name = name;
this.address = address;
}
}
發佈接口如下,其他部分不變。
@Slf4j
@RestController
public class PubController {
@Autowired
private RedisTemplate redisTemplate;
@GetMapping("/pub")
public void pub (String message){
log.info("eureka-client 發佈消息{}", message);
Employee employee = new Employee(message, "cn");
redisTemplate.convertAndSend("eureka-client", employee);
}
}
瀏覽器訪問http://localhost:2000/pub:
http://localhost:2000/pub?message=zz
日誌打印:
監聽到topic爲eureka-client的消息:[“lhc.wi.springcloud.bean.Employee”,{“name”:“zz”,“address”:“cn”}]
可以看到,依然可以正常使用。