redis pub/sub 之 spring-boot-starter-redis 代码片段

mvn pom

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.4</version>
        <relativePath/>
    </parent>

    <groupId>com.hb</groupId>
    <artifactId>play-redis-pubsub</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

 

消息监听

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.stereotype.Component;

/**
 * @author bo
 */
@Slf4j
@Component
public class RedisMsgListener extends MessageListenerAdapter {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void onMessage(Message message, byte[] bytes) {
        byte[] body = message.getBody();
        byte[] channel = message.getChannel();
        String msg = (String) redisTemplate.getStringSerializer().deserialize(body);
        String topic = (String) redisTemplate.getStringSerializer().deserialize(channel);
        log.info("listener 收到:{} --> {}",topic,msg);
    }

}

消息监听器容器

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.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;

/**
 * @author bo
 */
@Configuration
public class RedisPubSubConfig {

    /*
    RedisConnectionFactory 自动装配
    MessageListenerAdapter --> RedisMsgListener
     */
    @Bean
    RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory, MessageListenerAdapter listenerAdapter) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        /* 配置监听器-PatternTopic */
        container.addMessageListener(listenerAdapter, new PatternTopic("/try/send1"));
        container.addMessageListener(listenerAdapter, new PatternTopic("/try/send2"));
        return container;
    }
}

消息发送

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

/**
 * @author bo
 */
@Component
public class RedisMsgSender {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public void sendMsg(String topic, String data) {
        stringRedisTemplate.convertAndSend(topic, data);
    }
}

 

测试用例

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.concurrent.TimeUnit;

@Slf4j
@SpringBootTest
class PlayRedisPubsubApplicationTests {
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    RedisMsgSender redisMsgSender;

    @SneakyThrows
    @Test
    void sendMsg() {
        // 直接使用 StringRedisTemplate 发送
        stringRedisTemplate.convertAndSend("/try/send1","msg_body1");
        stringRedisTemplate.convertAndSend("/try/send2","msg_body2");
        // 自己封装其他业务逻辑
//        redisMsgSender.sendMsg("/try/send1","msg_body1");
//        redisMsgSender.sendMsg("/try/send2","msg_body2");
        log.info("send msg_body");
        TimeUnit.MINUTES.sleep(1);
    }
}

 

posted on 2022-02-27 20:14  guardianbo  阅读(128)  评论(0编辑  收藏  举报

导航