SpringBoot整合Redis

1. pom.xml中引入Redis相关包

请注意,这里我们排除了lettuce驱动,采用了jedis驱动

<!-- redis的依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<exclusions>
<!-- 不依赖Redis的异步客户端lettuce -->
<exclusion>
<groupId>io.lettuce</groupId>
<artifactId>lettuce-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- 引入Redis的客户端驱动 Jedis -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>

2. application.yml中配置Redis

这里给出的是部分配置,更多的配置可百度相关文档

spring:
redis:
database: 1 # Redis数据库编号,这里采用了1号数据库
host: 127.0.0.1 # 主机号
port: 6379 # 端口号
timeout: 10000 # 链接超时时间
# jedis配置
jedis:
pool:
max-idle: 20
min-idle: 5
max-active: -1
max-wait: -1

3. 初始化RedisTemplate

我将其放在com.xxx.xxx.config包下,统一配置文件存放路径。

这里序列化都采用StringRedisSerializer,可根据需求改写为Jackson2JsonRedisSerializer序列化器

package com.xxx.xxx.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
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.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer; /**
* redis配置类
*
* @author axiang
*/
@Configuration
public class RedisConfig {
/**
* 初始化RedisTemplate
*
* @param factory
* @return
*/
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
template.setConnectionFactory(factory);
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);
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
// key采用String的序列化方式
template.setKeySerializer(stringRedisSerializer);
// hash的key也采用String的序列化方式
template.setHashKeySerializer(stringRedisSerializer);
// value序列化方式采用String
template.setValueSerializer(stringRedisSerializer);
// hash的value序列化方式采用 String
template.setHashValueSerializer(stringRedisSerializer); // // value序列化方式采用jackson
// template.setValueSerializer(jackson2JsonRedisSerializer);
// // hash的value序列化方式采用jackson
// template.setHashValueSerializer(jackson2JsonRedisSerializer); template.afterPropertiesSet();
return template; }
}

4. 编写RedisUtils,二次封装RedisTemplate

根据业务需要,二次封装Redis模板类,方便直接调用。同时使用@Component注解将工具类注册为bean,交由spring容器管理

package com.xxx.xxx.component.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils; import java.util.concurrent.TimeUnit; /**
* Redis配置类
*
* @author axiang
*/
@Component
public class RedisUtils { @Autowired
private RedisTemplate<String, Object> redisTemplate; /**
* 指定缓存失效时间
*
* @param key
* @param time
* @return
*/
public boolean expire(String key, long time) {
if (time > 0) {
redisTemplate.expire(key, time, TimeUnit.SECONDS);
return true;
} else {
return false;
} } /**
* 根据key 获取过期时间
*
* @param key
* @return 时间(秒)
*/
public long getExpire(String key) {
return redisTemplate.getExpire(key, TimeUnit.SECONDS);
} /**
* 判断key是否存在
*
* @param key 键
* @return true 存在 false不存在
*/
public boolean hasKey(String key) {
return redisTemplate.hasKey(key);
} /**
* 删除缓存
*
* @param key 可以传一个值 或多个
*/
public void del(String... key) {
if (key != null && key.length > 0) {
if (key.length == 1) {
redisTemplate.delete(key[0]);
} else {
redisTemplate.delete(CollectionUtils.arrayToList(key));
}
}
} /*============================String=============================*/ /**
* 普通缓存获取
*
* @param key 键
* @return 值
*/ public Object get(String key) {
return StringUtils.isEmpty(key) ? null : redisTemplate.opsForValue().get(key);
} /**
* 普通缓存放入
*
* @param key 键
* @param value 值
* @return true成功 false失败
*/
public boolean set(String key, Object value) {
redisTemplate.opsForValue().set(key, value);
return true;
} /**
* 普通缓存放入并设置时间
*
* @param key 键
* @param value 值
* @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期
* @return true成功 false 失败
*/
public boolean set(String key, Object value, long time) {
if (time > 0) {
redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
} else {
set(key, value);
}
return true;
} }

5. 调用并测试功能

这里展示的代码为使用redis进行鉴权的操作类,仅展示Redis操作相关内容,鉴权实现请查看本博客其他内容

package com.xxx.xxx.component.redis;

import com.xxx.xxx.component.token.TokenManager;
import com.xxx.xxx.component.token.TokenModel; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils; /**
* token 在 redis 上的操作类,封装了对Redis的一些操作
*
* @author axiang
*/
@Component
public class RedisTokenManager implements TokenManager { @Autowired
RedisUtils redisUtils; /**
*
* @param username
* @return
*/
@Override
public TokenModel createToken(String username) {
String token = "xxx";
redisUtils.set(username, token);
return new TokenModel(username, token);
} @Override
public boolean checkToken(TokenModel model) {
if (null == model) {
return false;
}
String token;
token = (String) redisUtils.get(model.getUsername());
if (StringUtils.isEmpty(token) || !token.equals(model.getToken())) {
return false;
}
// 如果鉴权成功,延长过期时间
// redis.boundValueOps(model.getUsername()).expire();
return true;
} @Override
public String createAuth(TokenModel model) {
String username = model.getUsername();
String token = model.getToken();
String auth = username + "_" + token;
return auth; } @Override
public TokenModel getToken(String authentication) {
if (StringUtils.isEmpty(authentication)) {
return null;
}
String[] param = authentication.split("_");
int paramLength = 2;
if (paramLength != param.length) {
return null;
}
return new TokenModel(param[0], param[1]);
} @Override
public void deleteToken(String username) {
redisUtils.del(username);
}
}

【SpringBoot | Redis】SpringBoot整合Redis的更多相关文章

  1. SpringBoot缓存篇Ⅱ --- 整合Redis以及序列化机制

    一.Redis环境搭建 系统默认是使用ConcurrentMapCacheManager,然后获取和创建ConcurrentMapCache类型的缓存组件,再将数据保存在ConcurrentMap中 ...

  2. 【快学springboot】11.整合redis实现session共享

    前言 这里都是基于前面的项目基础上的.springboot整合redis非常的方便,这也是springboot的宗旨,简化配置.这篇文章就教大家如何使用springboot整合redis来实现sess ...

  3. 25、springboot与缓存整合Redis

    默认使用ConcurrentMapCacheManager 将数据保存在下面的Map中 docker: 安装Redis: 查看官方文档: 添加约束 <dependency> <gro ...

  4. springboot笔记10——整合Redis

    依赖 <dependencies> <!--web依赖--> <dependency> <groupId>org.springframework.boo ...

  5. springboot 2.x整合redis,spring aop实现接口缓存

    pox.xml: <dependency> <groupId>org.springframework.boot</groupId> <artifactId&g ...

  6. redis(Springboot中封装整合redis,java程序如何操作redis的5种基本数据类型)

    平常测试redis操作命令,可能用的是cmd窗口 操作redis,记录一下 java程序操作reids, 操作redis的方法 可以用Jedis ,在springboot 提供了两种 方法操作 Red ...

  7. SpringBoot学习:整合Redis

    项目下载地址:http://download.csdn.NET/detail/aqsunkai/9805821 pom.xml添加对redis的依赖: <!-- https://mvnrepos ...

  8. SpringBoot + MySQL + MyBatis 整合 Redis 实现缓存操作

    本地安装 Redis Redis 安装:https://www.cnblogs.com/oukele/p/11373052.html 项目结构:  SpringBootRedis 工程项目结构如下: ...

  9. SpringBoot:Shiro 整合 Redis

    前言 前段时间做了一个图床的小项目,安全框架使用的是Shiro.为了使用户7x24小时访问,决定把项目由单机升级为集群部署架构.但是安全框架shiro只有单机存储的SessionDao,尽管Shrio ...

  10. SpringBoot整合Redis(一)

    docker启动redis docker run -p 6379:6379 --name myredis redis 查看容器 [root@topcheer ~]# docker ps -l CONT ...

随机推荐

  1. 《Java并发编程实战》读书笔记-第5章 基础构建模块

    同步容器类 同步容器类实现线程安全的方式:将所有状态封装起来,对每个公有方法使用同步,使得每一次只有一个线程可以访问.同步容器类包含:Vector.Hashtable.Collections.sync ...

  2. CSAPP: 位操作实现基本运算

    目录 实验要求 实现代码 1.pow2plus1 2.pow2plus4 3.bitXor 4.tmin 5.isTmax 6.allOddBits 7.negate 8.isAsciiDigit 9 ...

  3. python学习-类的继承

    1.继承的语法 2.多继承 3.override(子类重写父类的方法) 4.子类调用父类中被重写的实例方法 5.使用super函数调用父类的构造方法

  4. canvas模拟中国铁路运行图

    原理说明 1.在知道canvas画布尺寸的情况下,需要将地理经纬度信息转换为canvas画布x,y坐标,因为中国地图地理经纬度坐标取值范围为73.33-135.05(经度)37-50(维度),所以第一 ...

  5. Java学习笔记二--API课堂记录

    JavaSE课堂记录(二) 第一节课 方法的重载:方法名相同,参数列表不同 方法的重写:方法名,参数列表相同 两同:方法名相同,参数列表相同 两小:访问权限小与等于父类,返回值类型小于等于父类(返回值 ...

  6. java 实现基于opencv全景图合成

    因项目需要,自己做了demo,从中学习很多,所以分享出来,希望有这方面需求的少走一些弯路,opencv怎么安装网上教程多多,这里不加详细说明,我安装的opencv-3.3.0 如上图所示,找到相应的j ...

  7. JVM 知识点补充——永久代和元空间

    之前已经讲过了不少有关 JVM 的内容,今天准备将之前没有细讲的部分进行补充,比如:永久代和元空间. 永久代 Java 的内存中有一块称之为方法区的部分,在 JDK8 之前, Hotspot 虚拟机中 ...

  8. 微信支付 get_brand_wcpay_request fail,Undefined variable: openid

    本文将为您描述微信H5支付,微信JSAPI支付返回支付签名验证失败的解决方法 微信JSAPI支付时报这个错误 查看错误详情 alert(JSON.stringify(res)) 微信商户平台相关设置: ...

  9. NetworkManager网络通讯_破产版NetworkManager(五)

    根据对NetWorkServer 以及NetworkClient的理解,编写一个简易版的NetWork Manager.惯例全部代码放在最后 (一)NetWorkServer与NetworkClien ...

  10. 找不到 cucumber.api.cli.Main 的报错解决方案

    最近玩IDEA,发现导入的项目有问题,报了一个“找不到或者不存在cucumber.api.cli.Main”的错误. 后来发现是新版的IDEA在导入时没有提示,以至于我没有配置项目对应的Tomcat服 ...