目录
1-在springboot项目的pom.xml
2-在application.properties中配置redis参数
3-编写redis的配置类
4-编写redis的工具类
5-测试类RedisController.java
在配置文件里加入redis的jar依赖
4.0.0
com.demo.springboot
springbootdemo
1.0-SNAPSHOT
org.springframework.boot
spring-boot-starter-parent
2.1.4.RELEASE
org.springframework.boot
spring-boot-starter-web
org.mybatis.spring.boot
mybatis-spring-boot-starter
1.3.0
org.springframework.boot
spring-boot-starter-test
test
com.alibaba
fastjson
1.2.58
com.github.pagehelper
pagehelper-spring-boot-starter
1.2.5
mysql
mysql-connector-java
5.1.39
org.springframework.boot
spring-boot-starter-aop
org.springframework.boot
spring-boot-starter-data-redis
org.projectlombok
lombok
1.8
org.springframework.boot
spring-boot-maven-plugin
spring.redis.host=192.168.3.25
spring.redis.port=6379
#连接超时
spring.redis.timeout=3000
#连接池最大阻塞等待时间,负值表示没有限制
spring.redis.jedis.pool.max-wait=30000
#连接池最大连接数,负值表示没有限制
spring.redis.jedis.pool.max-active=100
#连接池中最小空闲连接
spring.redis.jedis.pool.min-idle=0
#连接池中最大空闲连接
spring.redis.jedis.pool.max-idle=20
RedisConfig.java
RedisConnectionFactory 常用的有两种连接器的实现: Lettuce Connector 和 Jedis Connector,两种实现方式的配置也很简单,如下:
package com.swadian.redis.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
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.HashOperations;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/**
* @author swadian
* @date 2022/2/19
* @Version 1.0
* @describetion
*/
@Configuration
@EnableCaching //启用注解驱动的缓存
public class RedisConfig extends CachingConfigurerSupport {
/**
* retemplate相关配置
* @param factory->配置来源
* @return
*/
@Bean
public RedisTemplate redisTemplate( RedisConnectionFactory factory) {
RedisTemplate template = new RedisTemplate<>();
//1-配置连接工厂
template.setConnectionFactory(factory);
//2-使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
Jackson2JsonRedisSerializer jacksonSeial = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
//指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
//指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会跑出异常
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jacksonSeial.setObjectMapper(om);
//使用StringRedisSerializer来序列化和反序列化redis的key值
template.setKeySerializer(new StringRedisSerializer());
//值采用json序列化
template.setValueSerializer(jacksonSeial);
//设置hash key 和value序列化模式
template.setHashKeySerializer(new StringRedisSerializer());
template.setHashValueSerializer(jacksonSeial);
/**
* 初始化RedisTemplate
* 防止template not initialized; call afterPropertiesSet() before using it
*/
template.afterPropertiesSet();
return template;
}
/**
* 对hash类型的数据操作
*
* @param redisTemplate
* @return
*/
@Bean
public HashOperations hashOperations(RedisTemplate redisTemplate) {
return redisTemplate.opsForHash();
}
/**
* 对redis字符串类型数据操作
*
* @param redisTemplate
* @return
*/
@Bean
public ValueOperations valueOperations(RedisTemplate redisTemplate) {
return redisTemplate.opsForValue();
}
/**
* 对链表类型的数据操作
*
* @param redisTemplate
* @return
*/
@Bean
public ListOperations listOperations(RedisTemplate redisTemplate) {
return redisTemplate.opsForList();
}
/**
* 对无序集合类型的数据操作
*
* @param redisTemplate
* @return
*/
@Bean
public SetOperations setOperations(RedisTemplate redisTemplate) {
return redisTemplate.opsForSet();
}
/**
* 对有序集合类型的数据操作
*
* @param redisTemplate
* @return
*/
@Bean
public ZSetOperations zSetOperations(RedisTemplate redisTemplate) {
return redisTemplate.opsForZSet();
}
}
RedisUtil.java
package com.swadian.redis.utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* redisTemplate封装
*/
@Component
public class RedisUtil {
@Autowired
private RedisTemplate redisTemplate;
public RedisUtil(RedisTemplate redisTemplate) {
this.redisTemplate = redisTemplate;
}
/**
* 指定缓存失效时间
* @param key 键
* @param time 时间(秒)
* @return
*/
public boolean expire(String key,long time){
try {
if(time>0){
redisTemplate.expire(key, time, TimeUnit.SECONDS);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 根据key 获取过期时间
* @param key 键 不能为null
* @return 时间(秒) 返回0代表为永久有效
*/
public long getExpire(String key){
return redisTemplate.getExpire(key,TimeUnit.SECONDS);
}
/**
* 判断key是否存在
* @param key 键
* @return true 存在 false不存在
*/
public boolean hasKey(String key){
try {
return redisTemplate.hasKey(key);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 删除缓存
* @param key 可以传一个值 或多个
*/
@SuppressWarnings("unchecked")
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 key==null?null:redisTemplate.opsForValue().get(key);
}
/**
* 普通缓存放入
* @param key 键
* @param value 值
* @return true成功 false失败
*/
public boolean set(String key,Object value) {
try {
redisTemplate.opsForValue().set(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 普通缓存放入并设置时间
* @param key 键
* @param value 值
* @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期
* @return true成功 false 失败
*/
public boolean set(String key,Object value,long time){
try {
if(time>0){
redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
}else{
set(key, value);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 递增
* @param key 键
* @param delta 要增加几(大于0)
* @return
*/
public long incr(String key, long delta){
if(delta<0){
throw new RuntimeException("递增因子必须大于0");
}
return redisTemplate.opsForValue().increment(key, delta);
}
/**
* 递减
* @param key 键
* @param delta 要减少几(小于0)
* @return
*/
public long decr(String key, long delta){
if(delta<0){
throw new RuntimeException("递减因子必须大于0");
}
return redisTemplate.opsForValue().increment(key, -delta);
}
//================================Map=================================
/**
* HashGet
* @param key 键 不能为null
* @param item 项 不能为null
* @return 值
*/
public Object hget(String key,String item){
return redisTemplate.opsForHash().get(key, item);
}
/**
* 获取hashKey对应的所有键值
* @param key 键
* @return 对应的多个键值
*/
public Map
状态枚举Status.java
package com.swadian.redis.utils;
import java.util.concurrent.TimeUnit;
/**
* 状态枚举
*/
public abstract class Status {
/**
* 过期时间相关枚举
*/
public static enum ExpireEnum{
//未读消息的有效期为30天
UNREAD_MSG(30L, TimeUnit.DAYS)
;
/**
* 过期时间
*/
private Long time;
/**
* 时间单位
*/
private TimeUnit timeUnit;
ExpireEnum(Long time, TimeUnit timeUnit) {
this.time = time;
this.timeUnit = timeUnit;
}
public Long getTime() {
return time;
}
public TimeUnit getTimeUnit() {
return timeUnit;
}
}
}
package com.swadian.redis.controller;
import com.swadian.redis.utils.RedisUtil;
import com.swadian.userdemo.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
@Slf4j
@RequestMapping("/redis")
@RestController
public class RedisController {
private static int ExpireTime = 60; // redis中存储的过期时间60s
@Resource
private RedisUtil redisUtil;
@RequestMapping("set")
public boolean redisset(String key, String value) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
User user = new User();
user.setUserId(UUID.randomUUID().toString().replace("-", ""));
user.setUserName("Mike");
user.setUserAge(18);
user.setUserSex("男");
user.setCreateTime(simpleDateFormat.format(new Date()));
user.setUpdateTime(simpleDateFormat.format(new Date()));
redisUtil.set("userInfoCache", user);
return redisUtil.set("userInfoCache", user);
// return redisUtil.set(key, value);
}
@RequestMapping("get")
public Object redisget(String key) {
return redisUtil.get(key);
}
@RequestMapping("expire")
public boolean expire(String key) {
return redisUtil.expire(key, ExpireTime);
}
}
用的Postman工具测试。
返回:true 代表向redis中存成功,登陆redis客户端,可以看到缓存的数据
参考文档:
springboot redis 项目实战 完整篇 - 简书
springboot 整合 redis (RedisConnection RedisConnectionFactory Redis Template redis序列化)_Swing-CSDN博客_redisconnectionfactory