SpringBoot实战(七)之与Redis进行消息传递

此次教程演示安装的是Window版的Redis,

Linux安装Redis可以参考我的这篇博文:Redis的安装和客户端使用注意事项

关于Java连接Redis操作方面可以参考我的这篇博文:Java连接Redis之redis的增删改查

window安装Redis非常简单,就是下载+解压,启动服务端和客户端即可。

我是参考菜鸟教程的:http://www.runoob.com/redis/redis-install.html

包括,大家想熟悉和练练手,大家可以参考菜鸟教程,非常基础,也十分有利于提高学习信心和积极性的。

至于为什么使用Redis?

简单的说,如果我有上亿的数据,这些数据基本变动不大,如果我通过数据库加索引查询,是需要一定的时间的,如果我通过Redis将其缓存,那么通常是先缓存再数据库,意思是,如果缓存有,就不必查数据库了,要知道将数据缓存到内存中,通常CPU是直接跟内存进行交互,CPU+内存,这样会很大提升查询效率和速度的。而磁盘的话,就相对于慢的非常多。

这也是Redis一个应用场景之一。

就不多说基础方面的了,来一波示例讲解:

一、导入依赖

<?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>org.springframework</groupId>
    <artifactId>gs-messaging-redis</artifactId>
    <version>0.1.0</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.8.RELEASE</version>
    </parent>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
    </dependencies>


    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>spring-releases</id>
            <name>Spring Releases</name>
            <url>https://repo.spring.io/libs-release</url>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>spring-releases</id>
            <name>Spring Releases</name>
            <url>https://repo.spring.io/libs-release</url>
        </pluginRepository>
    </pluginRepositories>
</project>

二、编写消息接收类

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();
    }
}

三、编写配置文件

# Redisu6570u636Eu5E93u7D22u5F15uFF08u9ED8u8BA4u4E3A0uFF09
spring.redis.database=0
# Redisu670Du52A1u5668u5730u5740
spring.redis.host=localhost
# Redisu670Du52A1u5668u8FDEu63A5u7AEFu53E3
spring.redis.port=6379
# Redisu670Du52A1u5668u8FDEu63A5u5BC6u7801uFF08u9ED8u8BA4u4E3Au7A7AuFF09
spring.redis.password=
# u8FDEu63A5u6C60u6700u5927u8FDEu63A5u6570uFF08u4F7Fu7528u8D1Fu503Cu8868u793Au6CA1u6709u9650u5236uFF09
spring.redis.pool.max-active=8
# u8FDEu63A5u6C60u6700u5927u963Bu585Eu7B49u5F85u65F6u95F4uFF08u4F7Fu7528u8D1Fu503Cu8868u793Au6CA1u6709u9650u5236uFF09
spring.redis.pool.max-wait=-1
# u8FDEu63A5u6C60u4E2Du7684u6700u5927u7A7Au95F2u8FDEu63A5
spring.redis.pool.max-idle=8
# u8FDEu63A5u6C60u4E2Du7684u6700u5C0Fu7A7Au95F2u8FDEu63A5
spring.redis.pool.min-idle=0
# u8FDEu63A5u8D85u65F6u65F6u95F4uFF08u6BEBu79D2uFF09
spring.redis.timeout=0

四、编写启动类

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);
    }
}

成功标志:

原文地址:https://www.cnblogs.com/youcong/p/9386398.html