Spring Boot Sample 022之spring-boot-data-redis-lettuce

一世执手 提交于 2020-08-11 07:29:51

一、环境

  • Idea 2020.1
  • JDK 1.8
  • maven

二、目的

spring boot 通过lettuce整合redis

三、步骤

3.1、点击File -> New Project -> Spring Initializer,点击next

3.2、在对应地方修改自己的项目信息

3.3、选择Web依赖,选中Spring Web、Spring Boot Redis。可以选择Spring Boot版本,本次默认为2.2.7,点击Next

3.4、项目结构

四、添加文件

pom.xml文件
<?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.2.7.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>org.ouyushan</groupId>
    <artifactId>spring-boot-data-redis-jedis</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-boot-data-redis-jedis</name>
    <description>Jedis 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>
            <exclusions>
                <exclusion>
                    <groupId>io.lettuce</groupId>
                    <artifactId>lettuce-core</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>3.3.0</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </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>
application.properties文件
######## REDIS ########
# Redis数据库索引(默认为0)
spring.redis.database=0
# Redis服务器地址
spring.redis.host=127.0.0.1
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=
# 连接超时时间(毫秒)
spring.redis.timeout=3000
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.lettuce.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.lettuce.pool.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.lettuce.pool.max-idle=8
# 连接池中的最小空闲连接
spring.redis.lettuce.pool.min-idle=0
LettuceRedisConfig.java
package org.ouyushan.springboot.data.redis.lettuce.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import javax.annotation.Resource;
import java.util.Set;

/**
 * @Description:
 * @Author: ouyushan
 * @Email: ouyushan@hotmail.com
 * @Date: 2020/5/11 9:55
 */

@Configuration
@EnableCaching
public class LettuceRedisConfig {

    @Resource
    private LettuceConnectionFactory lettuceConnectionFactory;


    // 缓存管理器
    @Bean
    public RedisCacheManager cacheManager(RedisConnectionFactory lettuceConnectionFactory) {
        RedisCacheManager redisCacheManager = RedisCacheManager.builder(lettuceConnectionFactory).build();
        return redisCacheManager;
    }


    @Bean
    public RedisTemplate<Object, Object> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory) {
        RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(lettuceConnectionFactory);
        // key序列化
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        // 使用Jackson ,将对象序列化为JSON
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        //json 转对象类,不设置默认的会将json转成hashmap 报错:java.util.LinkedHashMap cannot be cast to XX
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);

        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }

}
package org.ouyushan.springboot.data.redis.jedis.entity;

import java.io.Serializable;

/**
 * @Description:
 * @Author: ouyushan
 * @Email: ouyushan@hotmail.com
 * @Date: 2020/5/9 14:03
 */
public class UserInfo implements Serializable {

    private static final long serialVersionUID = -6264728881593912971L;

    private Long id;

    private String userName;

    private String password;

    private int age;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "UserInfo{" +
                "id=" + id +
                ", userName='" + userName + '\'' +
                ", password='" + password + '\'' +
                ", age=" + age +
                '}';
    }
}

五、测试

运行以下测试用例验证String、Object、List以及Map在redis中的使用
SpringBootDataRedisJedisApplicationTests .java
package org.ouyushan.springboot.data.redis.lettuce;

import org.junit.jupiter.api.Test;
import org.ouyushan.springboot.data.redis.lettuce.entity.UserInfo;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.assertj.core.api.Assertions.assertThat;

@SpringBootTest
class SpringBootDataRedisLettuceApplicationTests {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedisTemplate redisTemplate;

    @Test
    public void testStringRedisTemplateForObject() {
        stringRedisTemplate.opsForValue().set("keyString", "valueString");
        String value = stringRedisTemplate.opsForValue().get("keyString");
        System.out.println(value);
        assertThat(value).isEqualTo("valueString");
    }

    @Test
    public void testRedisTemplateForObject() {
        UserInfo userInfo = new UserInfo();
        userInfo.setAge(24);
        userInfo.setId(1L);
        userInfo.setUserName("username");
        userInfo.setPassword("password");

        redisTemplate.opsForValue().set("object", userInfo);
        UserInfo userInfoFromRedis = (UserInfo) redisTemplate.opsForValue().get("object");
        System.out.println(userInfoFromRedis);
    }

    @Test
    public void testRedisTemplateForList() {
        UserInfo userInfo1 = new UserInfo();
        userInfo1.setAge(11);
        userInfo1.setId(1L);
        userInfo1.setUserName("username");
        userInfo1.setPassword("password");

        UserInfo userInfo2 = new UserInfo();
        userInfo2.setAge(21);
        userInfo2.setId(2L);
        userInfo2.setUserName("username");
        userInfo2.setPassword("password");

        List<UserInfo> list = new ArrayList<>();
        list.add(userInfo1);
        list.add(userInfo2);

        redisTemplate.opsForValue().set("list", list);
        List<UserInfo> userInfoFromRedis = (List) redisTemplate.opsForValue().get("list");
        System.out.println(userInfoFromRedis);
    }

    @Test
    public void testRedisTemplateForMap() {
        UserInfo userInfo1 = new UserInfo();
        userInfo1.setAge(11);
        userInfo1.setId(1L);
        userInfo1.setUserName("username");
        userInfo1.setPassword("password");

        UserInfo userInfo2 = new UserInfo();
        userInfo2.setAge(22);
        userInfo2.setId(2L);
        userInfo2.setUserName("username");
        userInfo2.setPassword("password");

        Map<String, UserInfo> map = new HashMap<>();
        map.put("userInfo1", userInfo1);
        map.put("userInfo2", userInfo2);

        redisTemplate.opsForValue().set("map", map);
        Map<String, UserInfo> userInfoFromRedis = (Map<String, UserInfo>) redisTemplate.opsForValue().get("map");
        System.out.println(userInfoFromRedis);
    }

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!