一、背景介绍

公司最近的新项目在进行技术框架升级,基于的Spring Boot的版本是2.0.2,整合Redis数据库。网上基于2.X版本的整个Redis少之又少,中间踩了不少坑,特此把整合过程记录,以供小伙伴们参考。

本文的基于在于会搭建Spring Boot项目的基础上进行的,入门是小白的话,请自行学习相关基础知识,网上或相关书籍很多。

由于我本人对Maven比较熟悉,所以是以Maven进行的。Gradle类似,核心思想都是一样的,实现项目管理工具不同而已。

二、整合过程

1.创建Spring Boot项目(2.0.2版本)

利用idea提供的接口进行创建,创建后目录结构如下:(请忽略mybatis.log4j2等相关代码和文件)

2.pom依赖

        <!-- Spring Boot Redis依赖 --><!-- 注意:1.5版本的依赖和2.0的依赖不一样,注意看哦 1.5我记得名字里面应该没有“data”, 2.0必须是“spring-boot-starter-data-redis” 这个才行--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId><!-- 1.5的版本默认采用的连接池技术是jedis  2.0以上版本默认连接池是lettuce, 在这里采用jedis,所以需要排除lettuce的jar --><exclusions><exclusion><groupId>redis.clients</groupId><artifactId>jedis</artifactId></exclusion><exclusion><groupId>io.lettuce</groupId><artifactId>lettuce-core</artifactId></exclusion></exclusions></dependency><!-- 添加jedis客户端 --><dependency><groupId>redis.clients</groupId><artifactId>jedis</artifactId></dependency><!--spring2.0集成redis所需common-pool2--><!-- 必须加上,jedis依赖此  --><!-- spring boot 2.0 的操作手册有标注 大家可以去看看 地址是:https://docs.spring.io/spring-boot/docs/2.0.3.RELEASE/reference/htmlsingle/--><dependency><groupId>org.apache.commons</groupId><artifactId>commons-pool2</artifactId><version>2.5.0</version></dependency><!-- 将作为Redis对象序列化器 --><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.47</version></dependency>

3.yml相关Redis配置

其实关于Redis的配置主要包括两方面,一时Redis的配置,一个是jedis pool连接池的配置

  1. yml具体配置如下
  2. Redis自定义配置

关于Redis的配置方式有很多,我知道有1.自动配置;2.手动配置;3.传统的xml文件也是可以的。在这里我只讲第2中,第二种比较灵活,符合spring boot风格。

  • 新建config包
  • 新建RedisConfiguration类
  package com.cherry.framework.config;import com.fasterxml.jackson.annotation.JsonAutoDetect;import com.fasterxml.jackson.annotation.PropertyAccessor;import com.fasterxml.jackson.databind.ObjectMapper;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Value;import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.cache.Cache;import org.springframework.cache.CacheManager;import org.springframework.cache.annotation.CachingConfigurerSupport;import org.springframework.cache.annotation.EnableCaching;import org.springframework.cache.interceptor.CacheErrorHandler;import org.springframework.cache.interceptor.KeyGenerator;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.jedis.JedisConnectionFactory;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;import org.springframework.data.redis.serializer.RedisSerializer;import org.springframework.data.redis.serializer.StringRedisSerializer;import redis.clients.jedis.JedisPool;import redis.clients.jedis.JedisPoolConfig;/*** Redis 配置类** @author Leon* @version 2018/6/17 17:46*/@Configuration// 必须加,使配置生效@EnableCachingpublic class RedisConfiguration extends CachingConfigurerSupport {/*** Logger*/private static final Logger lg = LoggerFactory.getLogger(RedisConfiguration.class);@Autowiredprivate JedisConnectionFactory jedisConnectionFactory;@Bean@Overridepublic KeyGenerator keyGenerator() {//  设置自动key的生成规则,配置spring boot的注解,进行方法级别的缓存// 使用:进行分割,可以很多显示出层级关系// 这里其实就是new了一个KeyGenerator对象,只是这是lambda表达式的写法,我感觉很好用,大家感兴趣可以去了解下return (target, method, params) -> {StringBuilder sb = new StringBuilder();sb.append(target.getClass().getName());sb.append(":");sb.append(method.getName());for (Object obj : params) {sb.append(":" + String.valueOf(obj));}String rsToUse = String.valueOf(sb);lg.info("自动生成Redis Key -> [{}]", rsToUse);return rsToUse;};}@Bean@Overridepublic CacheManager cacheManager() {// 初始化缓存管理器,在这里我们可以缓存的整体过期时间什么的,我这里默认没有配置lg.info("初始化 -> [{}]", "CacheManager RedisCacheManager Start");RedisCacheManager.RedisCacheManagerBuilder builder = RedisCacheManager.RedisCacheManagerBuilder.fromConnectionFactory(jedisConnectionFactory);return builder.build();}@Beanpublic RedisTemplate<String, Object> redisTemplate(JedisConnectionFactory jedisConnectionFactory ) {//设置序列化Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);ObjectMapper om = new ObjectMapper();om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);jackson2JsonRedisSerializer.setObjectMapper(om);// 配置redisTemplateRedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();redisTemplate.setConnectionFactory(jedisConnectionFactory);RedisSerializer stringSerializer = new StringRedisSerializer();redisTemplate.setKeySerializer(stringSerializer); // key序列化redisTemplate.setValueSerializer(jackson2JsonRedisSerializer); // value序列化redisTemplate.setHashKeySerializer(stringSerializer); // Hash key序列化redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer); // Hash value序列化redisTemplate.afterPropertiesSet();return redisTemplate;}@Override@Beanpublic CacheErrorHandler errorHandler() {// 异常处理,当Redis发生异常时,打印日志,但是程序正常走lg.info("初始化 -> [{}]", "Redis CacheErrorHandler");CacheErrorHandler cacheErrorHandler = new CacheErrorHandler() {@Overridepublic void handleCacheGetError(RuntimeException e, Cache cache, Object key) {lg.error("Redis occur handleCacheGetError:key -> [{}]", key, e);}@Overridepublic void handleCachePutError(RuntimeException e, Cache cache, Object key, Object value) {lg.error("Redis occur handleCachePutError:key -> [{}];value -> [{}]", key, value, e);}@Overridepublic void handleCacheEvictError(RuntimeException e, Cache cache, Object key)    {lg.error("Redis occur handleCacheEvictError:key -> [{}]", key, e);}@Overridepublic void handleCacheClearError(RuntimeException e, Cache cache) {lg.error("Redis occur handleCacheClearError:", e);}};return cacheErrorHandler;}/*** 此内部类就是把yml的配置数据,进行读取,创建JedisConnectionFactory和JedisPool,以供外部类初始化缓存管理器使用* 不了解的同学可以去看@ConfigurationProperties和@Value的作用**/@ConfigurationPropertiesclass DataJedisProperties{@Value("${spring.redis.host}")private  String host;@Value("${spring.redis.password}")private  String password;@Value("${spring.redis.port}")private  int port;@Value("${spring.redis.timeout}")private  int timeout;@Value("${spring.redis.jedis.pool.max-idle}")private int maxIdle;@Value("${spring.redis.jedis.pool.max-wait}")private long maxWaitMillis;@BeanJedisConnectionFactory jedisConnectionFactory() {lg.info("Create JedisConnectionFactory successful");JedisConnectionFactory factory = new JedisConnectionFactory();factory.setHostName(host);factory.setPort(port);factory.setTimeout(timeout);factory.setPassword(password);return factory;}@Beanpublic JedisPool redisPoolFactory() {lg.info("JedisPool init successful,host -> [{}];port -> [{}]", host, port);JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();jedisPoolConfig.setMaxIdle(maxIdle);jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);JedisPool jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout, password);return jedisPool;}}}

4.整合测试

在UserService的实现类中(业务层)进行缓存测试,注入RedisTemplate或StringRedisTemplate都可以。

package com.cherry.framework.service.impl;import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cherry.framework.dao.UserEntityMapper;
import com.cherry.framework.model.UserEntity;
import com.cherry.framework.service.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;import java.util.List;/*** User ServiceImpl** @author Leon* @version 2018/6/14 17:12*/
@Service
public class UserServiceImpl implements UserService {@AutowiredUserEntityMapper userEntityMapper;@AutowiredRedisTemplate redisTemplate;@AutowiredStringRedisTemplate stringRedisTemplate;/*** 新增** @param userEntity* @return*/@Override@Transactionalpublic int save(UserEntity userEntity) {userEntityMapper.insert(userEntity);return userEntity.getUserId();}/*** 查询所有** @return*/@Overridepublic PageInfo<UserEntity> findAllUserList(int pageNum, int pageSize) {PageHelper.startPage(pageNum, pageSize);List<UserEntity> list = userEntityMapper.selectAll();PageInfo<UserEntity> pageInfo = new PageInfo<>(list);// 具体使用redisTemplate.opsForList().leftPush("user:list", JSON.toJSONString(list));stringRedisTemplate.opsForValue().set("user:name", "张三");return pageInfo;}
}
  1. 使用postman访问对象controller的url
      /*** 列表查询** @return*/@RequestMapping(value = "/user/list")public PageInfo<UserEntity> findUserList(int pageNum, int pageSize) {PageInfo<UserEntity> pageInfo = userService.findAllUserList(pageNum, pageSize);return pageInfo;}
  1. 端口配置如下
  server:port: 8080servlet:path: /
  1. 访问url
  2. 通过Redis Desktop Manager 进行查看

三、总结

2.0整合在很多方面和1.5版本不一样,如果有问题参考官方英文文档,可以大大提高我们效率,(毕竟东西刚出,又没人翻译,只能看原版文档)

如果有说的不清楚的地方,在下面留言,我每天都会看博客,一起交流学习。最后晒出最后的总体结构图

Github地址:Spring Boot 2.X 整合Redis

SpringBoot之整合Redis分析和实现-基于Spring Boot2.0.2版本相关推荐

  1. Mongodb网页管理工具,基于Spring Boot2.0,前端采用layerUI实现

    源码:https://github.com/a870439570/Mongodb-WeAdmin 项目介绍 Mongodb网页管理工具,基于Spring Boot2.0,前端采用layerUI实现. ...

  2. Docker 部署 SpringBoot 项目整合 Redis 镜像做访问计数Demo

    Docker 部署SpringBoot项目整合 Redis 镜像做访问计数Demo 最终效果如下 大概就几个步骤 1.安装 Docker CE 2.运行 Redis 镜像 3.Java 环境准备 4. ...

  3. Redis(五)整合:SpringBoot如何整合Redis?

    前言 SpringBoot应该不用过多介绍了吧!是Spring当前最火的一个框架,既然学习了Redis,我们肯定是要在实际项目中使用,那么肯定首选整合SpringBoot啦! 简单介绍下SpringB ...

  4. springboot:整合redis之消息队列

    文章目录 springboot:整合redis之消息队列 一.项目准备 二.配置类 三.redis中list数据类型 定时器监听队列 运行即监控队列 四.发布/订阅模式 RedisConfig中添加监 ...

  5. Springboot:整合redis对接口数据进行缓存

    文章目录 Springboot:整合redis对接口数据进行缓存 一.注解及其属性介绍 @Cacheable @CacheEvict @CachePut @CacheConfig 二.代码实现 1.创 ...

  6. 基于spring boot2的个人博客系统

    welcome rodert 需要项目请直接到文章末尾获取 简介 基于spring boot2.mybatis.bootstrap开发的个人博客系统.下面做了功能和相关技术的描述,适合初学spring ...

  7. SpringBoot:整合Redis(概述,数据类型,持久化,RedisTemplate)

    1,Redis概述 1.1,Redis基本概念 在传统的Java Web项目中,使用数据库进行存储数据,但是有一些致命的弊端,这些弊端主要来自于性能方面.比如一些商品抢购的场景,或者是主页访问量瞬间较 ...

  8. springBoot+dubbo整合Redis - 脚手架系列(三)

    1.介绍 Redis(Remote Dictionary Server) 是一个使用 C 语言编写的,开源的(BSD许可)高性能非关系型(NoSQL)的键值对数据库. Redis 可以存储键和五种不同 ...

  9. Springboot项目整合redis集群

    文章目录 1.redis集群搭建 详情见: https://blog.csdn.net/qq_45076180/article/details/103026150 2.springboot整合redi ...

最新文章

  1. SQLSERVER 2008 R2 事务日志已满
  2. 传感器信号 如何发送到服务器,传感器如何将消息发送给云服务器
  3. 一道没人搞得定的趣味Shell编程游戏题!,看看你会不会?
  4. wordpress本地网站怎么搬到服务器,如何把wordpress从本地服务器迁徙到网站主机上...
  5. java float 运算_java基础之float、double底层运算
  6. 美团/饿了么外卖返利小程序+公众号PHP三级分销源码下载
  7. [转载]Codejock Xtreme ToolkitPro MFC 使用
  8. 5款App帮你创建时间轴
  9. 微博运营的5个经典案例
  10. [机器学习] 信用评分卡中的应用 | 干货
  11. 电机是怎么转的?(电机原理+电机控制+电机分类)
  12. 电脑播放视频报错----------无法播放。请确保你的计算机的声卡和视频卡可以使用,并安装了最新的驱动程序----------解决!
  13. 创意十足的多媒体沙盘展示,为企业品牌宣传效果锦上添花
  14. 计算机中乘法是什么函数,excl中的乘法函数符号是什么
  15. 从《雪白血红》说起(1)
  16. ppc64le处理器国产power8服务器CentOS7.2安装ibm-jdk
  17. win10虚拟机创建
  18. Android 日历提供器(二)
  19. IDEA奇YIN巧技
  20. 通达OA 2016系统连接ORACLE 11g数据库(图文)

热门文章

  1. 药品名自动归类机器人
  2. 计算几何2- 判断两线段是否相交
  3. Android 虚拟运营商apn与spn配置
  4. 吃得苦中苦 方为人上人
  5. 【数据库系统概念第七版(Database System Concepts 7th)配套SQL文件如何获取】
  6. mp4转换成gif怎么转?
  7. H5新特性有哪些?怎么理解语义化
  8. 解决微信小程序“app.json: [“workers“] 字段需为 目录“错误及worker的使用
  9. javac -d,-cp是什么意思
  10. 环信 即时通讯sdk实现客服功能