译:9.使用Redis进行消息传递

本指南引导您完成使用Spring Data Redis发布和订阅经过Redis发送的消息的过程。Messaging with Redishtml

1. 咱们将构建什么?

您将构建一个使用StringRedisTemplate发布字符串消息的应用程序,并使用MessageListenerAdapter为其提供POJO订阅。java

使用Spring Data Redis做为发布消息的手段可能听起来很奇怪,但正如您将发现的那样,Redis不只提供了NoSQL数据存储,还提供了消息传递系统。git

 2. 咱们须要准备什么?

3.  如何完成这个指南?

 像大多数Spring入门指南同样,您能够从头开始并完成每一个步骤,也能够绕过已熟悉的基本设置步骤。 不管哪一种方式,你最终获得工做代码。

为了兼顾没法使用Intellij Idea 的读者,我这里依然采用STS来完成这个指南。

1. 打开咱们的STS ,New ————> Import Spring Getting Started Content

2.  输入message, 搜索找到Message Redis

Tips: Code Sets 咱们仍然所有勾选,这样系统默认会生成一个已经写好的complete 项目,这样方便咱们在Initial项目中模仿学习。

3.  搭建Redis 服务器

在构建消息传递应用程序以前,您须要设置将处理接收和发送消息的服务器。

Redis是一个开源的BSD许可的键值数据存储器,它还附带了一个消息传递系统。 

3.1 在Windows 操做系统安装Redis 

关于Redis 在windows 上的安装详情可参考个人另一篇博文:  揭开Redis的神秘面纱

3.2 启动Redis 服务器

下载安装好后,你若是没有配置环境变量须要先进入Redis 安装文件夹

好比咱们的安装在C:\app\Redis\Redis-x64-3.2.100 那么咱们打开命令行窗口后,执行如下命令进入安装文件夹:

C:\app\Redis\Redis-x64-3.2.100

 Tips: 若是已经配置了环境变量能够跳过上述步骤

而后咱们执行启动Redis 服务器命令

redis-serve

执行成功后你会看到下面图示的内容:

Tips: 若是看到上述内容,说明服务器启动成功,端口监听在6379端口

 4. 建立一个Redis消息接收器

在任何基于消息传递的应用程序中,都有消息发布者和消息接收者。 要建立消息接收方,请使用一种方法来实现接收方以响应消息:

src/main/java/hello/Receiver.java

package hello;

import java.util.concurrent.CountDownLatch;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

public class Receiver {
    private static final Logger LOGGER=LoggerFactory.getLogger(Receiver.class);
    
    private CountDownLatch latch;
    
    @Autowired
    public Receiver(CountDownLatch latch) {
        this.latch=latch;
    }

    public void receiveMessage(String message) {
        LOGGER.info("Received <" +message+">");
        latch.countDown();
    }
}

Receiver是一个简单的POJO,它定义了一种接收消息的方法。 正如您将Receiver注册为消息侦听器时所看到的,您能够根据须要命名消息处理方法。

出于演示的目的,它的构造函数使用倒计数锁存器进行自动装配。 这样,它能够在收到消息时发出信号。

5. 注册侦听器并发送消息

Spring Data Redis提供了使用Redis发送和接收消息所需的全部组件。 具体来讲,你须要配置:

  • 链接工厂
  • 消息侦听器容器
  • Redis模板

您将使用Redis模板发送消息,而且您将向Receiver注册消息侦听器容器,以便它能够接收消息。 链接工厂驱动模板和消息侦听器容器,使它们可以链接到Redis服务器。

本示例使用Spring Boot的默认RedisConnectionFactory,它是基于Jedis Redis库的JedisConnectionFactory的一个实例。 链接工厂被注入到消息监听器容器和Redis模板中。

src/main/java/hello/Application.java

package hello;

import java.util.concurrent.CountDownLatch;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;

@SpringBootApplication
public class Application {

    private static final Logger LOGGER=LoggerFactory.getLogger(Application.class);
    
    @Bean
    RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,MessageListenerAdapter listenerAdapter) {
        RedisMessageListenerContainer container=new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        container.addMessageListener(listenerAdapter,new PatternTopic("chat"));
        return container;
    }
    
    @Bean
    MessageListenerAdapter listenerAdapter(Receiver receiver) {
        return new MessageListenerAdapter(receiver,"receiveMessage");
    }
    
    @Bean
    Receiver receiver(CountDownLatch latch) {
        return new Receiver(latch);
    }
    
    @Bean
    CountDownLatch latch() {
        return new CountDownLatch(1);
    }
    
    @Bean
    StringRedisTemplate template(RedisConnectionFactory connectionFactory) {
        return new StringRedisTemplate(connectionFactory);
    }
    
    public static void main(String[] args)throws InterruptedException{
        ApplicationContext ctx=SpringApplication.run(Application.class,args);
        
        StringRedisTemplate template=ctx.getBean(StringRedisTemplate.class);
        CountDownLatch latch = ctx.getBean(CountDownLatch.class);
        
        LOGGER.info("Sending message...");
        template.convertAndSend("chat", "Hello from Redis!");

        latch.await();
        System.exit(0);
    }
}

在listenerAdapter方法中定义的bean在容器中定义的消息侦听器容器中注册为消息侦听器,并将侦听“chat”主题上的消息。

因为Receiver类是POJO,所以须要将其包装在实现AddMessageListener()所需的MessageListener接口的消息侦听器适配器中。

消息侦听器适配器还配置为在消息到达时调用Receiver上的receiveMessage()方法。

链接工厂和消息监听器容器bean都是您须要侦听消息的。

要发送消息,您还须要一个Redis模板。在这里,它是一个配置为StringRedisTemplate的bean,它是RedisTemplate的一个实现,它着重于Redis的经常使用用法,其中键和值都是`String`s。

main()方法经过建立Spring应用程序上下文来解决全部问题。应用程序上下文而后启动消息监听器容器,而且消息监听器容器bean开始监听消息。而后,main()方法从应用程序上下文中检索StringRedisTemplate bean,并使用它发送“来自Redis的Hello!”消息在“chat”主题上。最后,它关闭Spring应用程序上下文并结束应用程序。

6. 编译成可执行Jar

您能够使用Gradle或Maven从命令行运行应用程序。 或者您能够构建一个包含全部必需的依赖项,类和资源的可执行JAR文件,并运行该文件。 这使得在整个开发生命周期内跨越不一样环境等,将服务做为应用程序发布,版本化和部署变得很是容易。

生成Jar 

若是您正在使用Gradle,则能够使用./gradlew bootRun运行该应用程序。 或者您能够使用./gradlew构建构建JAR文件。 而后你能够运行JAR文件:

java -jar build/libs/gs-messaging-redis-0.1.0.jar

若是您使用的是Maven,则能够使用./mvn spring-boot:run来运行该应用程序。 或者您能够使用./mvn clean包构建JAR文件。 而后你能够运行JAR文件:

java -jar target/gs-messaging-redis-0.1.0.jar

上述过程将建立一个可运行的JAR。 您也能够选择构建经典的WAR文件。

7. 执行成功后你将看到下面的信息:


 恭喜! 您刚刚使用Spring和Redis开发了一个简单的发布和订阅应用程序。

源码:点击查看

相关文章
相关标签/搜索