SpringBoot 是为了简化 Spring 应用的创建、运行、调试、部署等一系列问题而诞生的产物,自动装配的特性让我们可以更好的关注业务本身而不是外部的XML配置,我们只需遵循规范,引入相关的依赖就可以轻易的搭建出一个 WEB 工程

Spring Boot 除了支持常见的ORM框架外,更是对常用的中间件提供了非常好封装,随着Spring Boot2.x的到来,支持的组件越来越丰富,也越来越成熟,其中对Redis的支持不仅仅是丰富了它的API,更是替换掉底层Jedis的依赖,取而代之换成了Lettuce(生菜)

Redis介绍

Redis是一个开源的使用ANSI C语言编写、支持网络、可基于内存亦可持久化的日志型、Key-Value数据库,并提供多种语言的API。相比Memcached它支持存储的类型相对更多字符哈希集合有序集合列表GEO同时Redis是线程安全的。2010年3月15日起,Redis的开发工作由VMware主持,2013年5月开始,Redis的开发由Pivotal赞助。

Lettuce

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

导入依赖

在 pom.xml 中spring-boot-starter-data-redis的依赖,Spring Boot2.x 后底层不在是Jedis如果做版本升级的朋友需要注意下

  1. 1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
  1. <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.apache.commons</groupId>
    <artifactId>commons-pool2</artifactId>
    </dependency>
    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
    </dependency>

属性配置

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

  1. 1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
  1. spring.redis.host=localhost
    spring.redis.password=battcn
    # 连接超时时间(毫秒)
    spring.redis.timeout=10000
    # Redis默认情况下有16个分片,这里配置具体使用的分片,默认是0
    spring.redis.database=0
    # 连接池最大连接数(使用负值表示没有限制) 默认 8
    spring.redis.lettuce.pool.max-active=8
    # 连接池最大阻塞等待时间(使用负值表示没有限制) 默认 -1
    spring.redis.lettuce.pool.max-wait=-1
    # 连接池中的最大空闲连接 默认 8
    spring.redis.lettuce.pool.max-idle=8
    # 连接池中的最小空闲连接 默认 0
    spring.redis.lettuce.pool.min-idle=0

具体编码

Spring BootRedis的支持已经非常完善了,良好的序列化以及丰富的API足够应对日常开发

实体类

创建一个User

  1. 1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
  1. package com.battcn.entity;
  2.  
  3. import java.io.Serializable;
  4.  
  5. /**
    * @author Levin
    * @since 2018/5/10 0007
    */
    public class User implements Serializable {
  6.  
  7. private static final long serialVersionUID = 8655851615465363473L;
    private Long id;
    private String username;
    private String password;
    // TODO 省略get set
    }

自定义Template

默认情况下的模板只能支持RedisTemplate<String, String>,也就是只能存入字符串,这在开发中是不友好的,所以自定义模板是很有必要的,当自定义了模板又想使用String存储这时候就可以使用StringRedisTemplate的方式,它们并不冲突…

  1. 1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
  1. package com.battcn.config;
  2.  
  3. import org.springframework.boot.autoconfigure.AutoConfigureAfter;
    import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
    import org.springframework.data.redis.serializer.StringRedisSerializer;
  4.  
  5. import java.io.Serializable;
  6.  
  7. /**
    * TODO 修改database
    *
    * @author Levin
    * @since 2018/5/10 0022
    */
    @Configuration
    @AutoConfigureAfter(RedisAutoConfiguration.class)
    public class RedisCacheAutoConfiguration {
  8.  
  9. @Bean
    public RedisTemplate<String, Serializable> redisCacheTemplate(LettuceConnectionFactory redisConnectionFactory) {
    RedisTemplate<String, Serializable> template = new RedisTemplate<>();
    template.setKeySerializer(new StringRedisSerializer());
    template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
    template.setConnectionFactory(redisConnectionFactory);
    return template;
    }
    }

测试

完成准备事项后,编写一个junit测试类来检验代码的正确性,有很多人质疑过Redis线程安全性,故下面也提供了响应的测试案例,如有疑问欢迎指正

  1. 1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
  1. package com.battcn;
  2.  
  3. import com.battcn.entity.User;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    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;
  4.  
  5. import java.io.Serializable;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import java.util.stream.IntStream;
  6.  
  7. /**
    * @author Levin
    * @since 2018/5/10 0010
    */
    @RunWith(SpringRunner.class)
    @SpringBootTest
    public class Chapter8ApplicationTest {
  8.  
  9. private static final Logger log = LoggerFactory.getLogger(Chapter8ApplicationTest.class);
  10.  
  11. @Autowired
    private StringRedisTemplate stringRedisTemplate;
  12.  
  13. @Autowired
    private RedisTemplate<String, Serializable> redisCacheTemplate;
  14.  
  15. @Test
    public void get() {
    // TODO 测试线程安全
    ExecutorService executorService = Executors.newFixedThreadPool(1000);
    IntStream.range(0, 1000).forEach(i ->
    executorService.execute(() -> stringRedisTemplate.opsForValue().increment("kk", 1))
    );
    stringRedisTemplate.opsForValue().set("k1", "v1");
    final String k1 = stringRedisTemplate.opsForValue().get("k1");
    log.info("[字符缓存结果] - [{}]", k1);
    // TODO 以下只演示整合,具体Redis命令可以参考官方文档,Spring Data Redis 只是改了个名字而已,Redis支持的命令它都支持
    String key = "battcn:user:1";
    redisCacheTemplate.opsForValue().set(key, new User(1L, "u1", "pa"));
    // TODO 对应 String(字符串)
    final User user = (User) redisCacheTemplate.opsForValue().get(key);
    log.info("[对象缓存结果] - [{}]", user);
    }
    }

其它类型

下列的就是Redis其它类型所对应的操作方式

  • opsForValue: 对应 String(字符串)
  • opsForZSet: 对应 ZSet(有序集合)
  • opsForHash: 对应 Hash(哈希)
  • opsForList: 对应 List(列表)
  • opsForSet: 对应 Set(集合)
  • opsForGeo: 对应 GEO(地理位置)

总结

spring-data-redis文档: https://docs.spring.io/spring-data/redis/docs/2.0.1.RELEASE/reference/html/#new-in-2.0.0
Redis 文档: https://redis.io/documentation
Redis 中文文档: http://www.redis.cn/commands.html

整合Lettuce Redis的更多相关文章

  1. springBoot 官方整合的redis 使用教程:(StringRedisTemplate 方式存储 Object类型value)

    前言:最近新项目准备用 redis 简单的缓存 一些查询信息,以便第二次查询效率高一点. 项目框架:springBoot.java.maven  说明:edis存储的数据类型,key一般都是Strin ...

  2. springboot整合mybatis,redis,代码(二)

    一 说明: springboot整合mybatis,redis,代码(一) 这个开发代码的复制粘贴,可以让一些初学者直接拿过去使用,且没有什么bug 二 对上篇的说明 可以查看上图中文件: 整个工程包 ...

  3. Mybatis整合(Redis、Ehcache)实现二级缓存

    目的: Mybatis整合Ehcache实现二级缓存 Mybatis整合Redis实现二级缓存 Mybatis整合ehcache实现二级缓存 ssm中整合ehcache 在POM中导入相关依赖 < ...

  4. springMVC整合jedis+redis,以注解形式使用

    前两天写过 springMVC+memcached 的整合,我从这个基础上改造一下,把redis和springmvc整合到一起. 和memcached一样,redis也有java专用的客户端,官网推荐 ...

  5. springMVC整合jedis+redis

    http://www.cnblogs.com/zhengbn/p/4140549.html 前两天写过 springMVC+memcached 的整合,我从这个基础上改造一下,把redis和sprin ...

  6. springboot整合mybatis,redis,代码(一)

    一 搭建项目,代码工程结构 使用idea或者sts构建springboot项目 二  数据库sql语句 SQLyog Ultimate v12.08 (64 bit) MySQL - 5.7.14-l ...

  7. SpringBoot整合集成redis

    Redis安装:https://www.cnblogs.com/zwcry/p/9505949.html 1.pom.xml <project xmlns="http://maven. ...

  8. springboot整合mybatis,redis,代码(四)

    一 说明 这是spring整合redis注解开发的系类: 二 正文 在注解开发时候,会有这几个注解需要注意: 具体含义: 1.@Cacheable 可以标记在方法上,也可以标记在类上.当标记在方法上时 ...

  9. Spring Boot (23) Lettuce Redis

    Spring Boot除了支持常见的ORM框架外,更是对常用的中间件提供了非常好的封装,随着SpringBoot2.x的到来,支持的组件也越来越丰富,也越来越成熟,其中对Redis的支持不仅仅是它丰富 ...

随机推荐

  1. Java实现 蓝桥杯VIP 算法训练 数的划分

    [题目描述] 将整数n分成k份,且每份不能为空,任意两份不能相同(不考虑顺序). 例如:n=7,k=3,下面三种分法被认为是相同的. 1,1,5: 1,5,1: 5,1,1: 问有多少种不同的分法. ...

  2. 如何获取CSDN的积分?

    个人感觉就是写博客就给积分 具体给多少? CSDN应该有自己的积分规则 总之一句话:写博客涨积分

  3. Java实现 LeetCode 83 删除排序链表中的重复元素

    83. 删除排序链表中的重复元素 给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次. 示例 1: 输入: 1->1->2 输出: 1->2 示例 2: 输入: 1-> ...

  4. Java实现 LeetCode 67 二进制求和

    67. 二进制求和 给定两个二进制字符串,返回他们的和(用二进制表示). 输入为非空字符串且只包含数字 1 和 0. 示例 1: 输入: a = "11", b = "1 ...

  5. 第五届蓝桥杯C++B组国(决)赛真题

    解题代码部分来自网友,如果有不对的地方,欢迎各位大佬评论 题目1.年龄巧合 小明和他的表弟一起去看电影,有人问他们的年龄.小明说:今年是我们的幸运年啊.我出生年份的四位数字加起来刚好是我的年龄.表弟的 ...

  6. Java实现LeetCode_0013_RomanToInteger

    package javaLeetCode.primary; import java.util.HashMap; import java.util.Map; import java.util.Scann ...

  7. java实现第四届蓝桥杯猜灯谜

    猜灯谜 题目描述 A 村的元宵节灯会上有一迷题: 请猜谜 * 请猜谜 = 请边赏灯边猜 小明想,一定是每个汉字代表一个数字,不同的汉字代表不同的数字. 请你用计算机按小明的思路算一下,然后提交&quo ...

  8. Java学习之斐波那契数列实现

    描述 一个斐波那契序列,F(0) = 0, F(1) = 1, F(n) = F(n-1) + F(n-2) (n>=2),根据n的值,计算斐波那契数F(n),其中0≤n≤1000. 输入 输入 ...

  9. 【asp.net core 系列】6 实战之 一个项目的完整结构

    0. 前言 在<asp.net core 系列>之前的几篇文章中,我们简单了解了路由.控制器以及视图的关系以及静态资源的引入,让我们对于asp.net core mvc项目有了基本的认识. ...

  10. Flask flush 闪现

    闪现 要用必须导入 flash , get_flashed_messages flash 用于存闪现的值.他有两个参数,1 messsage,用来存储信息 2 category ,用于给信息分类,该参 ...