Spring Boot StringRedisTemplate 发布订阅

导读:本篇文章讲解 Spring Boot StringRedisTemplate 发布订阅,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

概述

引入依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
        </dependency>

配置

spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=123456
spring.redis.database=0
# 连接超时时间(毫秒)
spring.redis.timeout=10000
# 连接池最大阻塞等待时间(使用负值表示没有限制) 默认 -1
spring.redis.lettuce.pool.max-wait=300
# 连接池中的最大空闲连接
spring.redis.lettuce.pool.max-idle=10
# 连接池中的最小空闲连接
spring.redis.lettuce.pool.min-idle=5
# 连接池最大连接数(使用负值表示没有限制) 默认 8
spring.redis.lettuce.pool.max-active=100

监听代码

package com.china.system.service;
 
import org.springframework.data.redis.connection.MessageListener;
 
/**
 * Redis 订阅
 *
 * @author songjy
 */
public interface RedisSubscribeService extends MessageListener {
}

package com.china.system.service.impl;
 
import com.china.system.service.RedisSubscribeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
 
import java.util.Objects;
 
/**
 * redis 订阅:https://docs.spring.io/spring-data/data-redis/docs/current/reference/html/#pubsub
 *
 * @author songjy
 */
@Component
@Slf4j
public class RedisSubscribeServiceImpl extends MessageListenerAdapter implements RedisSubscribeService {
 
    @Override
    public void onMessage(@Nullable Message message, byte[] bytes) {
 
        if (Objects.isNull(message)) {
            log.error("消息为空");
            return;
        }
 
        String channel = new String(message.getChannel());
        String body = new String(message.getBody());
        log.info("订阅频道:{}{}消息:{}", channel, System.lineSeparator(), body);
    }
}

监听配置

package com.china.system.config;
 
import com.china.system.service.RedisSubscribeService;
import com.google.common.collect.Lists;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
 
/**
 * @author songjy
 */
@Configuration
public class RedisConfig {
 
    @Bean
    public RedisMessageListenerContainer redisMessageListenerContainer(RedisConnectionFactory connectionFactory,
                                                                       RedisSubscribeService redisSubscribeService) {
        RedisMessageListenerContainer redisMessageListenerContainer = new RedisMessageListenerContainer();
        redisMessageListenerContainer.setConnectionFactory(connectionFactory);
        redisMessageListenerContainer.addMessageListener(redisSubscribeService, Lists.newArrayList(
                ChannelTopic.of("song"),
                ChannelTopic.of("jian"),
                ChannelTopic.of("yong")
        ));
        return redisMessageListenerContainer;
    }
}

消息发布

package com.china.system.service;
 
/**
 * Redis 发布
 *
 * @author songjy
 */
public interface RedisPublishService {
    /**
     * 发布消息
     *
     * @param channel 频道
     * @param message 消息
     */
    void sendMessage(String channel, String message);
}

package com.china.system.service.impl;
 
import com.china.system.service.RedisPublishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
 
/**
 * @author songjy
 */
@Component
@Slf4j
public class RedisPublishServiceImpl implements RedisPublishService {
    private StringRedisTemplate stringRedisTemplate;
 
    @Autowired
    public void setStringRedisTemplate(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }
 
    @Override
    public void sendMessage(String channel, String message) {
        if (StringUtils.isBlank(message)) {
            return;
        }
        stringRedisTemplate.convertAndSend(channel, message);
        log.info("频道【{},{}】消息已发布", channel, message);
    }
}

消息发布订阅单元测试

package com.china.system.service.impl;
 
import com.china.system.RedisDemoApplication;
import com.china.system.service.RedisPublishService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
 
import java.util.concurrent.TimeUnit;
 
@SpringBootTest(classes = {RedisDemoApplication.class})
@RunWith(SpringRunner.class)
@Transactional
@Slf4j
@Data
@ActiveProfiles("beta")
public class RedisPublishServiceImplTests {
    private RedisPublishService redisPublishService;
 
    @Autowired
    public void setRedisPublishService(RedisPublishService redisPublishService) {
        this.redisPublishService = redisPublishService;
    }
 
    @Test
    public void sendMessageTest() throws InterruptedException {
        redisPublishService.sendMessage("song", "song" + System.currentTimeMillis());
        redisPublishService.sendMessage("jian", "jian" + System.currentTimeMillis());
        redisPublishService.sendMessage("yong", "yong" + System.currentTimeMillis());
        log.info("消息发布完毕");
        TimeUnit.SECONDS.sleep(5L);
    }
}

参考

Spring Boot StringRedisTemplate 发布订阅

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/99914.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!