La publicación y suscripción de Redis (pub / sub) es un modo de comunicación de mensajes: el remitente (pub) envía el mensaje y el suscriptor (sub) recibe el mensaje.
Los clientes de Redis pueden suscribirse a cualquier número de canales.
El siguiente ejemplo demuestra cómo funciona la publicación y la suscripción. Deben abrirse dos clientes redis-cli:
En nuestro ejemplo, hemos creado un canal de suscripción llamado sms:
SUBSCRIBE sms
Ahora, primero reiniciamos un cliente de redis y luego publicamos dos mensajes en el mismo canal sms, los suscriptores pueden recibir el mensaje:
PUBLISH sms "hello sms"
El cliente del suscriptor mostrará el siguiente mensaje
cliente java
archivo 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>
Archivo de configuración
spring:
redis:
host: 127.0.0.1
port: 6379
database: 0
Clase de supervisión de mensajes 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;
}
});
}
}
Supervisión de mensajes clase 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);
}
}
}
Clase de prueba
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;
}
});
}
}