redis公開およびサブスクライブモード

Redisの発行とサブスクライブ(pub / sub)は、メッセージ通信モードです。送信者(pub)がメッセージを送信し、サブスクライバー(sub)がメッセージを受信します。

Redisクライアントは、任意の数のチャネルにサブスクライブできます。

次の例は、公開とサブスクライブの仕組みを示しています。2つのredis-cliクライアントを開く必要があります。
この例では、smsという名前のサブスクリプションチャネルを作成しました。

SUBSCRIBE sms 

ここに写真の説明を挿入

ここで、最初にredisクライアントを再起動してから、同じチャネルsmsで2つのメッセージを公開すると、サブスクライバーはメッセージを受信できます。

PUBLISH sms "hello sms"

ここに写真の説明を挿入
サブスクライバーのクライアントは次のメッセージを表示します
ここに写真の説明を挿入

javaクライアント

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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.sunyuqi</groupId>
    <artifactId>redis_demo</artifactId>
    <version>1.0-SNAPSHOT</version>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.3.RELEASE</version>
        <relativePath/> 
    </parent>
    <properties>
        <java.version>9</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

</project>

構成ファイル

spring:
  redis:
    host: 127.0.0.1
    port: 6379
    database: 0

メッセージ監視クラス1

package com.sunyuqi.pubsub;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;

@Component
@Profile("pubsub")
public class SmsChannelListener1 {
    
    

    @Autowired
    RedisTemplate redisTemplate;

    @PostConstruct
    public void setup() {
    
    
        redisTemplate.execute(new RedisCallback() {
    
    
            @Override
            public Object doInRedis(RedisConnection connection) throws DataAccessException {
    
    
                connection.subscribe((message, pattern) -> {
    
    
                    System.out.println("监听器1收到消息: " + message);
                }, "sms".getBytes());
                return null;
            }
        });
    }
}

メッセージ監視クラス2

package com.sunyuqi.pubsub;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Component
@Profile("pubsub")
@Configuration
public class SmsChannelListener2 {
    
    
    // 定义监听器
    @Bean
    public RedisMessageListenerContainer smsMessageListener(RedisConnectionFactory redisConnectionFactory) {
    
    
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(redisConnectionFactory);
        SmsSendListener smsSendListener = new SmsSendListener();
        container.addMessageListener(smsSendListener, Arrays.asList(new ChannelTopic("sms")));
        return container;
    }

    class SmsSendListener implements MessageListener {
    
    
        @Override
        public void onMessage(Message message, byte[] pattern) {
    
    
            System.out.println("监听器2收到消息: " + message);
        }
    }
}

テストクラス

package com.sunyuqi.pubsub;

import com.sunyuqi.SpringbootApplicationDemo;
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.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringbootApplicationDemo.class)
@ActiveProfiles("pubsub")
public class PubsubTest {
    
    

    @Autowired
    RedisTemplate redisTemplate;

    @Test
    public void test1() throws InterruptedException {
    
    
        System.out.println("开始测试发布订阅机制");
        redisTemplate.execute(new RedisCallback<Long>() {
    
    
            @Override
            public Long doInRedis(RedisConnection connection) throws DataAccessException {
    
    
                // 发送通知
                Long received = connection.publish("sms".getBytes(), "hello world".getBytes());
                return received;
            }
        });
    }
}

ここに写真の説明を挿入

おすすめ

転載: blog.csdn.net/weixin_42494845/article/details/108897194