【简约入门】将你的springboot项目加上Redis缓存

这是我参与11月更文挑战的第1天,活动详情查看:[2021最后一次更文挑战]
(juejin.cn/post/702364… "juejin.cn/post/702364…")

RedisTemplateSpring Data Redis提供给用户的最高级的抽象客户端,用户可直接通过RedisTemplate进行多种操作,redis的安装可参照文章:# 【简约入门】从Redis开始理解缓存

spring-data-redis功能介绍

客户端对比
  • jedis:采用直连的方式,多线程操作是不安全的。如果要规避多线程不安全要使用jedis pool连接池。BIO模式
  • lettuce:采用netty,实例可以在多个线程中共享,不存在线程不安全的情况。可以减少线程数量。NIO模式
spring-data-redis功能
  • 连接池自动管理,提供了一个高度封装的RedisTemplate
  • 进行了归类封装,将同一类型操作封装为operation接口
    • ValueOperations:简单K-V操作
    • SetOperations:set类型数据操作
    • ZSetOperations:zset类型数据操作
    • HashOperations:针对map类型的数据操作
    • ListOperations:针对list类型的数据操作
  • 提供了对key的bound(绑定)便捷化操作API,可以通过bound封装指定的key,然后进行一系列的操作而无须"显式"的再次指定Key,即BoundKeyOperations
  • 将事务操作封装,有容器控制。
  • 针对数据的"序列化/反序列化",提供了多种可选择策略(RedisSerializer)

开始配置redis

版本说明
  • maven: 3.5.4
  • java: jdk8
  • springboot: 2.0.5
  • spring-data-redis: 2.0.5
添加maven依赖
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
复制代码
添加配置
spring:
  redis:
    # Redis服务器地址
    host: localhost
    # Redis服务器密码(默认为空)
    password: 
    # Redis服务器端口
    port: 6379 
    # Redis数据库索引(默认情况下有16个分片,这里配置具体使用的分片,默认为0)
    database: 8 
    # Redis服务器连接超时时间(毫秒)
    timeout: 5000 
复制代码
添加工具类

增加redis hash结构的操作工具类,设置缓存方法,查询缓存方法

@Component
public class RedisUtils {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }
     /**
     * HashGet
     *
     * @param key  键 不能为null
     * @param item 项 不能为null
     * @return 值
     */
    public Object hget(String key, String item) {
        return redisTemplate.opsForHash().get(key, item);
    }
	
	
	/**
     * 向一张hash表中放入数据,如果不存在将创建
     *
     * @param key   键
     * @param item  项
     * @param value 值
     * @return true 成功 false失败
     */
    public boolean hset(String key, String item, Object value) {
        try {
            redisTemplate.opsForHash().put(key, item, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
复制代码
测试

使用Map放入测试数据,并查询打印

Map<String, Object> nameMap = new HashMap<>();
nameMap.put("name","faker");
redisUtils.hset("key123", "1", JsonMapper.defaultMapper().toJson(nameMap));

String value = (String) redisUtils.hget("key123", "1");
Map<String, Object> map = JSON.parseObject(value,Map.class);
System.out.println(map);
复制代码

spring redis 配置项说明

配置项 默认值 说明
spring.redis.client-name - Client name to be set on connections with CLIENT SETNAME.
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. This represents an "initial" list of cluster nodes and is required to have at least one entry.
spring.redis.database 0.0 Database index used by the connection factory.
spring.redis.host localhost Redis 服务器端IP地址
spring.redis.jedis.pool.max-active 8.0 在指定的时间,连接池可以分配的最大活跃连接数;设置负数代表无限制.
spring.redis.jedis.pool.max-idle 8.0 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.0 Target for the minimum number of idle connections to maintain in the pool. This setting only has an effect if both it and time between eviction runs are positive.
spring.redis.jedis.pool.time-between-eviction-runs - Time between runs of the idle object evictor thread. When positive, the idle object evictor thread starts, otherwise no idle object eviction is performed.
spring.redis.lettuce.cluster.refresh.adaptive false Whether adaptive topology refreshing using all available refresh triggers should be used.
spring.redis.lettuce.cluster.refresh.period - Cluster topology refresh period.
spring.redis.lettuce.pool.max-active 8.0 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.0 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.0 Target for the minimum number of idle connections to maintain in the pool. This setting only has an effect if both it and time between eviction runs are positive.
spring.redis.lettuce.pool.time-between-eviction-runs - Time between runs of the idle object evictor thread. When positive, the idle object evictor thread starts, otherwise no idle object eviction is performed.
spring.redis.lettuce.shutdown-timeout 100ms 关闭延迟时间.
spring.redis.password - redis 服务器的登录密码.
spring.redis.port 6379.0 Redis 服务器端端口号
spring.redis.sentinel.master - Redis 服务器器名称.
spring.redis.sentinel.nodes - Comma-separated list of "host:port" pairs.
spring.redis.sentinel.password - Password for authenticating with sentinel(s).
spring.redis.ssl false false时候开启SSL支持.
spring.redis.timeout - 链接过期时间。
spring.redis.url - 链接 URL. 包括 host, port,和 password. User被忽略,例如: redis://user:password@example.com:6379

小结

springboot与redis整合非常简单,使用spring-boot-starter-data-redis这个依赖,配置自己的连接信息,就可以连上redis进行简单操作了。