Spring Boot StringRedisTemplate 发布订阅

概述

引入依赖

        <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 发布订阅

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Spring Boot 中实现发布订阅模式,可以使用 Spring 的事件机制来实现。下面是一个简单的示例: 1. 创建一个事件类,例如 `MyEvent`: ```java public class MyEvent { private String message; public MyEvent(String message) { this.message = message; } public String getMessage() { return message; } } ``` 2. 创建一个事件发布者,例如 `EventPublisher`: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.stereotype.Component; @Component public class EventPublisher { @Autowired private ApplicationContext applicationContext; public void publishEvent(String message) { MyEvent event = new MyEvent(message); applicationContext.publishEvent(event); } } ``` 3. 创建一个事件监听器,例如 `EventListener`: ```java import org.springframework.context.event.EventListener; import org.springframework.stereotype.Component; @Component public class EventListener { @EventListener public void handleEvent(MyEvent event) { String message = event.getMessage(); // 处理事件 System.out.println("收到事件:" + message); } } ``` 4. 在需要发布事件的地方注入 `EventPublisher`,并调用 `publishEvent` 方法来发布事件: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class MyApp { @Autowired private EventPublisher eventPublisher; public static void main(String[] args) { SpringApplication.run(MyApp.class, args); } public void someMethod() { // 发布事件 eventPublisher.publishEvent("Hello, world!"); } } ``` 当调用 `someMethod` 方法时,会触发 `MyEvent` 事件的发布,然后 `EventListener` 中的 `handleEvent` 方法会被自动调用,从而实现了发布订阅模式。 这是一个简单的示例,你可以根据具体需求进行扩展和定制。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

融极

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值