Springboot 集成redis,来写一个发布订阅吧

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”}]

可以看到,依然可以正常使用。

猜你喜欢

转载自blog.csdn.net/TP89757/article/details/101677775