spring boot中redis使用

panda-star發表於2020-10-15

spring boot中redis使用

一、簡介

這裡介紹在spring boot中redis的使用,包含常規使用以及基於佇列的使用。

二、示例

2.1 新增maven依賴

<?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.3.3.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.dragon.study</groupId>
    <artifactId>spring_boot_data_redis</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring_boot_data_redis</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</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-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

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

</project>

2.2 定義配置檔案application.yaml

application.yaml如下:

spring:
  application:
    name: spring-boot-data-redis
  redis:
    host: localhost
    port: 6379
    database: 0
server:
  port: 10018

2.3 定義監聽處理類

監聽處理類ReflectRedisMqListener.java

package com.dragon.study.spring_boot_data_redis.redisMq;
import org.springframework.stereotype.Component;
@Component
public class ReflectRedisMqListener {
    //基於direct的訊息處理
    public void directMsgDispose(String msg){
        System.out.println("ReflectRedisMqListener directMsgDispose msg: "+ msg);
    }
    //基於topic的訊息處理
    public void topicMsgDispose(String msg){
        System.out.println("ReflectRedisMqListener topicMsgDispose msg: "+ msg);
    }
}

2.4 定義redis配置類

package com.dragon.study.spring_boot_data_redis.redisMq;
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.ChannelTopic;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import javax.annotation.Resource;

@Configuration
public class RedisMqConfig {
    @Resource
    private RedisConnectionFactory redisConnectionFactory;
    @Resource
    private ReflectRedisMqListener reflectRedisMqListener;

    @Bean
    public RedisMessageListenerContainer redisMessageListenerContainer() {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(redisConnectionFactory);
        container.addMessageListener(directMessageListenerAdapter(), new ChannelTopic("direct"));  //繫結topicMessageListenerAdapter監控器到指定通道direct
        container.addMessageListener(topicMessageListenerAdapter(), new PatternTopic("topic*"));  //繫結topicMessageListenerAdapter監控器到模糊匹配通道topic*
        return container;
    }

    @Bean
    public MessageListenerAdapter directMessageListenerAdapter(){
        return new MessageListenerAdapter(reflectRedisMqListener,"directMsgDispose");//通過反射,由ReflectRedisMqListener類的topicMsgDispose處理訊息
    }

    @Bean
    public MessageListenerAdapter topicMessageListenerAdapter(){
        return new MessageListenerAdapter(reflectRedisMqListener,"topicMsgDispose");//通過反射,由ReflectRedisMqListener類的topicMsgDispose處理訊息
    }
}

2.5 定義配置類

package com.dragon.study.spring_boot_data_redis;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@SpringBootApplication
public class SpringBootDataRedisApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootDataRedisApplication.class, args);
    }


}

2.6 測試

測試前先啟動SpringBootDataRedisApplication,開啟redis監聽,接著定義測試類如下:

package com.dragon.study.spring_boot_data_redis;

import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.StringRedisTemplate;
import javax.annotation.Resource;
import java.util.Set;

@SpringBootTest
class SpringBootDataRedisApplicationTests {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    //訊息測試
    @Test
    void redisListenerTest() {
        stringRedisTemplate.convertAndSend("topic", "topic_msg1");
        stringRedisTemplate.convertAndSend("topicOne", "topic_msg2");
        stringRedisTemplate.convertAndSend("topicTwo", "topic_msg3");
        stringRedisTemplate.convertAndSend("direct", "direct_msg1");
    }

    //常規測試
    @Test
    void redisTest() {
        //對string操作
        stringRedisTemplate.opsForValue().set("k6", "v6");
        Object vaObject = stringRedisTemplate.opsForValue().get("k6");

        //對list操作
        stringRedisTemplate.opsForList().rightPush("q", "one");
        Object o = stringRedisTemplate.opsForList().leftPop("q");

        //對hash操作
        stringRedisTemplate.opsForHash().put("h", "k1", "v1");
        Object hashObject = stringRedisTemplate.opsForHash().get("h", "k1");

        //對set操作
        stringRedisTemplate.opsForSet().add("s", "v1", "v2");
        Object setObject = stringRedisTemplate.opsForSet().pop("s");

        //對zset有序集合操作,最後一個引數為元素分數
        stringRedisTemplate.opsForZSet().add("zs", "v1", 99);
        stringRedisTemplate.opsForZSet().add("zs", "v2", 89);
        Set scoreZset = stringRedisTemplate.opsForZSet().rangeByScore("zs", 90, 100);
        Set zset = stringRedisTemplate.opsForZSet().range("zs", 0, 0);
    }
}

相關文章