SpringBoot学习笔记十:整合Redis

Spring Boot 2.x对Redis的支持,最大的改变莫过于替换掉底层Jedis的依赖,替换成Luttuce

Redis简介

以下内容摘自Redis中文网:
Redis 是一个开源(BSD许可)的,内存中的数据结构存储系统,它可以用作数据库、缓存和消息中间件。 它支持多种类型的数据结构,如 字符串(strings), 散列(hashes), 列表(lists), 集合(sets), 有序集合(sorted sets) 与范围查询, bitmaps, hyperloglogs 和 地理空间(geospatial) 索引半径查询。 Redis 内置了 复制(replication),LUA脚本(Lua scripting), LRU驱动事件(LRU eviction),事务(transactions) 和不同级别的 磁盘持久化(persistence), 并通过 Redis哨兵(Sentinel)和自动 分区(Cluster)提供高可用性(high availability)。

Redis英文官网为:https://redis.io/

Lettuce

Luttuce官网:https://lettuce.io/

Luttuce官网

LettuceJedis 的都是连接Redis Server的客户端程序。Jedis实现上是直连redis server,多线程环境下非线程安全,除非使用连接池,为每个Jedis实例增加物理连接Lettuce基于Netty的连接实例(StatefulRedisConnection),可以在多个线程间并发访问,且线程安全,满足多线程环境下的并发访问,同时它是可伸缩的设计,一个连接实例不够的情况也可以按需增加连接实例

Spring Boot整合Redis

导入依赖


    org.springframework.boot
    spring-boot-starter-data-redis


    org.apache.commons
    commons-pool2

相关配置

Spring Boot整合Redis的自动配置类为org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration,属性类为org.springframework.boot.autoconfigure.data.redis.RedisProperties

application.yml
在 application.yml 文件中配置如下内容,由于Spring Boot 2.x 的改动,连接池相关配置需要通过spring.redis.lettuce.pool 或者 spring.redis.jedis.pool 进行配置

spring:
  redis:
    host: localhost
    port: 6379
    password: 3096
    database: 0
    timeout: 5000ms           # 连接超时时间
    lettuce:
      pool:
        max-active: 8         # 连接池最大连接数(使用负值表示没有限制) 默认 8
        max-wait: -1ms        # 连接池最大阻塞等待时间(使用负值表示没有限制) 默认 -1
        max-idle: 8           # 连接池中的最大空闲连接 默认 8
        min-idle: 0           # 连接池中的最小空闲连接 默认 0

这里贴出Spring Boot关于RedisProperties的所有配置项

# REDIS RedisProperties
spring.redis.cluster.max-redirects= # Maximum number of redirects to follow when executing commands across the cluster.
spring.redis.cluster.nodes= # Comma-separated list of "host:port" pairs to bootstrap from.
spring.redis.database=0 # Database index used by the connection factory.
spring.redis.url= # Connection URL. Overrides host, port, and password. User is ignored. Example: redis://user:[email protected]:6379
spring.redis.host=localhost # Redis server host.
spring.redis.jedis.pool.max-active=8 # Maximum number of connections that can be allocated by the pool at a given time. Use a negative value for no limit.
spring.redis.jedis.pool.max-idle=8 # Maximum number of "idle" connections in the pool. Use a negative value to indicate an unlimited number of idle connections.
spring.redis.jedis.pool.max-wait=-1ms # Maximum amount of time a connection allocation should block before throwing an exception when the pool is exhausted. Use a negative value to block indefinitely.
spring.redis.jedis.pool.min-idle=0 # Target for the minimum number of idle connections to maintain in the pool. This setting only has an effect if it is positive.
spring.redis.lettuce.pool.max-active=8 # Maximum number of connections that can be allocated by the pool at a given time. Use a negative value for no limit.
spring.redis.lettuce.pool.max-idle=8 # Maximum number of "idle" connections in the pool. Use a negative value to indicate an unlimited number of idle connections.
spring.redis.lettuce.pool.max-wait=-1ms # Maximum amount of time a connection allocation should block before throwing an exception when the pool is exhausted. Use a negative value to block indefinitely.
spring.redis.lettuce.pool.min-idle=0 # Target for the minimum number of idle connections to maintain in the pool. This setting only has an effect if it is positive.
spring.redis.lettuce.shutdown-timeout=100ms # Shutdown timeout.
spring.redis.password= # Login password of the redis server.
spring.redis.port=6379 # Redis server port.
spring.redis.sentinel.master= # Name of the Redis server.
spring.redis.sentinel.nodes= # Comma-separated list of "host:port" pairs.
spring.redis.ssl=false # Whether to enable SSL support.
spring.redis.timeout= # Connection timeout.

具体编码

实体类

src/main/java/com/example/springbootredis/entity/User

package com.example.springbootredis.entity;

import java.io.Serializable;

public class User implements Serializable {

    private static final long serialVersionUID = 4811614273890733625L;

    private Long id;

    private String username;

    private String password;

    // setters and getters
}

自定义template

Spring Boot在RedisAutoConfiguration中默认配置了RedisTemplate、StringRedisTemplate两个模板类,而RedisTemplate并未指定key、value的序列化器,使用起来可能不那么顺手,因此自定义一个RedisTemplate是必要的

@Configuration
@ConditionalOnClass({RedisOperations.class})
@EnableConfigurationProperties({RedisProperties.class})
@Import({LettuceConnectionConfiguration.class, JedisConnectionConfiguration.class})
public class RedisAutoConfiguration {
    public RedisAutoConfiguration() {
    }

    @Bean
    @ConditionalOnMissingBean(
        name = {"redisTemplate"}
    )
    public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
        RedisTemplate template = new RedisTemplate();
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }

    @Bean
    @ConditionalOnMissingBean
    public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
        StringRedisTemplate template = new StringRedisTemplate();
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }
}

src/main/java/com/example/springbootredis/config/RedisConfig

package com.example.springbootredis.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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;

import java.io.Serializable;

@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate redisTemplate = new RedisTemplate<>();
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        return redisTemplate;
    }

}

测试

package com.example.springbootredis;

import com.example.springbootredis.entity.User;
import org.junit.Assert;
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.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.IntStream;

@RunWith(SpringRunner.class)
@SpringBootTest
public class RedisTest {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Test
    public void setTest() {
        redisTemplate.opsForValue().set("one", "1");

        stringRedisTemplate.opsForValue().set("two", "2");

        redisTemplate.opsForValue().set("user:1", new User(1L, "jack123", "123456789"));

        ExecutorService executorService = Executors.newFixedThreadPool(1000);
        IntStream.range(0, 1000).forEach(i -> {
            executorService.execute(() -> stringRedisTemplate.opsForValue().increment("num", 1));
        });
    }

    @Test
    public void getTest() {
        Object one = redisTemplate.opsForValue().get("one");
        Assert.assertEquals("1", one);

        String two = stringRedisTemplate.opsForValue().get("two");
        Assert.assertEquals("2", two);

        User user = (User) redisTemplate.opsForValue().get("user:1");
        Assert.assertEquals("jack123", user.getUsername());
    }
}

测试通过,看一下redis

127.0.0.1:6379> keys *
1) "one"
2) "two"
3) "num"
4) "user:1"
127.0.0.1:6379> get num
"1000"
127.0.0.1:6379> get user:1
"{\"@class\":\"com.example.springbootredis.entity.User\",\"id\":1,\"username\":\"jack123\",\"password\":\"123456789\"}"

使用Jedis

参考Spring Boot官方文档 91.4 Use Jedis Instead of Lettuce

导入Jedis依赖

这里首先需要在spring-boot-starter-data-redis中排除Luttuce依赖,再引入Jedis依赖

Maven


    org.springframework.boot
    spring-boot-starter-data-redis
    
        
            io.lettuce
            lettuce-core
        
    


    redis.clients
    jedis


    org.apache.commons
    commons-pool2

Gradle

configurations {
    compile.exclude module: "lettuce"
}

dependencies {
    compile("redis.clients:jedis")
    // ...
}

属性配置

将spring.redis.lettuce.pool 替换为 spring.redis.jedis.pool 即可,其他接连信息不变
application.yml

spring:
  redis:
    host: localhost
    port: 6379
    password: 3096
    database: 0
    timeout: 5000ms           # 连接超时时间
    jedis:
      pool:
        max-active: 8         # 连接池最大连接数(使用负值表示没有限制) 默认 8
        max-wait: -1ms        # 连接池最大阻塞等待时间(使用负值表示没有限制) 默认 -1
        max-idle: 8           # 连接池中的最大空闲连接 默认 8
        min-idle: 0           # 连接池中的最小空闲连接 默认 0

你可能感兴趣的:(SpringBoot学习笔记十:整合Redis)