前言
这篇文章只要记录SpringBoot与Redis的整合方式,关于Redis的基础本文不做讲解。
一、导入依赖
新建springboot项目,导入redis需要的依赖。
<!--redis依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
二、配置Redis地址
在springboot.properties配置文件里,增加redis的相关配置,此处使用redis集群的配置方式。
#redis-sentinel
spring.redis.sentinel.master=sentinel12.112.133.111
spring.redis.password=12345678
spring.redis.sentinel.nodes=12.112.133.111:26379,12.112.133.222:26379,12.112.133.333:26379
三、Redis配置类
/**
* @Desc 基于RedisTemplate的配置类
*/
@Configuration
public class RedisConfig {
/**
* @Desc 基于RedisTemplate的配置类
* @Author 自定义RedisTemplate
* @Date 2022.11.02
*/
@Bean
@SuppressWarnings("all")
public RedisTemplate<String, Object> leRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
//Json序列化配置
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);
//String序列化配置
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
//key采用Stirng序列化方式
template.setKeySerializer(stringRedisSerializer);
template.setHashKeySerializer(stringRedisSerializer);
//value采用json序列化方式
template.setValueSerializer(jackson2JsonRedisSerializer);
template.setHashValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
}
四、SpringUtils工具类
/**
* @Desc 获取Bean的工具
*/
@Component
public class SpringUtils implements ApplicationContextAware {
private static ApplicationContext applicationContext;
/**
* 重写接口的方法,该方法的参数为框架自动加载的IOC容器对象
* 该方法在启动项目的时候会自动执行,前提是该类上有IOC相关注解,例如@Component
*/
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
// 通过 beanName 获取 Bean
@SuppressWarnings("unchecked")
public static <T> T getBean(String beanName) {
return (T) applicationContext.getBean(beanName);
}
// 通过 beanName 获取 Bean
@SuppressWarnings("unchecked")
public static <T> T getBean(Class<?> clazz) {
return (T) applicationContext.getBean(clazz);
}
}
五、封装Redis工具类
/**
* @Desc Redis工具类
*/
@Slf4j
@SuppressWarnings("unchecked")
public final class RedisUtil {
private static final RedisTemplate<String, Object> redisTemplate = SpringUtils.getBean("leRedisTemplate");
/*******************存储普通对象操作*********************/
/**
* @Desc String数据类型,存入普通对象并设置过期时间
* @Author yangshuai11
* @Date 2022.11.07
*/
public static void set(String key, Object value, long timeout) {
try {
redisTemplate.opsForValue().set(key, value, timeout, TimeUnit.SECONDS);
} catch (Exception e) {
log.error("Redis存入普通对象时出错!key:" + key + ";value:" + value);
}
}
/**
* @Desc String数据类型,存入缓存
* @Author yangshuai11
* @Date 2022.11.02
*/
public static void set(String key, Object value) {
try {
redisTemplate.opsForValue().set(key, value);
} catch (Exception e) {
log.error("Redis存入普通对象时出错!key:" + key + ";value:" + value);
}
}
/**
* @Desc String数据类型,读取缓存数据
* @Author yangshuai11
* @Date 2022.11.02
*/
public static <T> T get(String key) {
try {
return (T) redisTemplate.opsForValue().get(key);
} catch (Exception e) {
log.error("Redis读取普通对象时出错!key:{},e:{}",key,e);
return null;
}
}
/*******************存储Hash操作*********************/
/**
* @Desc 往Hash中存入数据
* @Author yangshuai11
* @Date 2022.11.02
*/
public static void hPut(String key, String field, Object value) {
try {
redisTemplate.opsForHash().put(key, field, value);
} catch (Exception e) {
log.error("Redis存入Hash对象时出错!key:" + key + ";field:" + field + ";value:" + value);
}
}
/**
* @Desc 往Hash中存入多个数据
* @Author yangshuai11
* @Date 2022.11.02
*/
public static void hPutAll(String key, Map<String, Object> values) {
try {
redisTemplate.opsForHash().putAll(key, values);
} catch (Exception e) {
log.error("Redis存入Hash对象时出错!key:" + key + ";value:" + values);
}
}
/**
* @Desc 获取Hash中的数据
* @Author yangshuai11
* @Date 2022.11.02
*/
public static <T> T hGet(String key, String field) {
try {
return (T) redisTemplate.opsForHash().get(key, field);
} catch (Exception e) {
log.error("Redis读取Hash对象时出错!key:" + key + ";field:" + field);
return null;
}
}
/**
* @Desc 获取多个Hash中的数据
* @Author yangshuai11
* @Date 2022.11.02
*/
public static <V> List<V> hMultiGet(String key, Collection<Object> fields) {
try {
return (List<V>) redisTemplate.opsForHash().multiGet(key, fields);
} catch (Exception e) {
log.error("Redis读取Hash对象时出错!key:" + key + ";fields:" + fields);
return null;
}
}
/*******************存储Set相关操作*********************/
/**
* @Desc 往Set中存入数据
* @Author yangshuai11
* @Date 2022.11.07
*/
public static long sSet(String key, Object... values) {
try {
Long count = redisTemplate.opsForSet().add(key, values);
return count == null ? 0 : count;
} catch (Exception e) {
log.error("Redis存入Set对象时出错!key:" + key + ";values:" + Arrays.toString(values));
return 0;
}
}
/**
* @Desc 读取Set中的全部数据
* @Author yangshuai11
* @Date 2022.11.07
*/
public static <V> Set<V> sGetAll(String key) {
try {
return (Set<V>) redisTemplate.opsForSet().members(key);
} catch (Exception e) {
log.error("Redis读取Set全部对象时出错!key:" + key);
return null;
}
}
/**
* @Desc 往Set删除数据
* @Author yangshuai11
* @Date 2022.11.07
*/
public static long sDel(String key, Object... values) {
try {
Long count = redisTemplate.opsForSet().remove(key, values);
return count == null ? 0 : count;
} catch (Exception e) {
log.error("Redis删除Set对象时出错!key:" + key + ";values:" + Arrays.toString(values));
return 0;
}
}
/*******************存储List相关操作*********************/
/**
* @Desc 往List中存入数据
* @Author yangshuai11
* @Date 2022.11.07
*/
public static long lPush(String key, Object value) {
try {
Long count = redisTemplate.opsForList().rightPush(key, value);
return count == null ? 0 : count;
} catch (Exception e) {
log.error("Redis存入List对象时出错!key:" + key + ";value:" + value);
return 0;
}
}
/**
* @Desc 往List中存入多个数据
* @Author yangshuai11
* @Date 2022.11.07
*/
public static long lPushAll(String key, Collection<Object> values) {
try {
Long count = redisTemplate.opsForList().rightPushAll(key, values);
return count == null ? 0 : count;
} catch (Exception e) {
log.error("Redis存入List对象时出错!key:" + key + ";values:" + values);
return 0;
}
}
/**
* @Desc 往List中存入多个数据
* @Author yangshuai11
* @Date 2022.11.07
*/
public static long lPushAll(String key, Object... values) {
try {
Long count = redisTemplate.opsForList().rightPushAll(key, values);
return count == null ? 0 : count;
} catch (Exception e) {
log.error("Redis存入List对象时出错!key:" + key + ";values:" + Arrays.toString(values));
return 0;
}
}
/**
* @Desc 从List中获取begin到end之间的元素
* @Author yangshuai11
* @Date 2022.11.07
*/
public static <V> List<V> lGet(String key, int start, int end) {
try {
return (List<V>) redisTemplate.opsForList().range(key, start, end);
} catch (Exception e) {
log.error("Redis读取List对象时出错!key:" + key);
return null;
}
}
/**
* @Desc 从List中获取所有元素
* @Author yangshuai11
* @Date 2022.11.07
*/
public static <V> List<V> lGetAll(String key) {
try {
return (List<V>) redisTemplate.opsForList().range(key, 0, -1);
} catch (Exception e) {
log.error("Redis读取List对象时出错!key:" + key);
return null;
}
}
/*******************存储Zset相关操作*********************/
/**
* @Desc 往ZSet中存入数据
* @Author yangshuai11
* @Date 2022.11.10
*/
public static void zSet(String key, Object value, double score) {
try {
redisTemplate.opsForZSet().add(key, value, score);
} catch (Exception e) {
log.error("Redis存入ZSet对象时出错!key:" + key + ";value:" + value + ";score:" + score);
}
}
/**
* @Desc 获取ZSet某集合下的全部数据
* @Author yangshuai11
* @Date 2022.11.10
*/
public static <V> Set<V> zGetAll(String key) {
try {
//按照排名先后(从小到大)打印指定区间内的元素, -1为打印全部
return (Set<V>) redisTemplate.opsForZSet().range(key, 0, -1);
} catch (Exception e) {
log.error("Redis获取ZSet的全部文件时出错!key:" + key);
return null;
}
}
/**
* @Desc 返回Zset集合内元素在指定分数范围内的排名(从小到大)
* @Author yangshuai11
* @Date 2022.11.10
*/
public static <V> Set<V> zRangeByScore(String key, double startScore, double endScore) {
try {
//返回Zset集合内元素在指定分数范围内的排名(从小到大)
return (Set<V>) redisTemplate.opsForZSet().rangeByScore(key, startScore, endScore);
} catch (Exception e) {
log.error("Redis获取ZSet时出错!key:" + key);
return null;
}
}
/**
* @Desc 删除ZSet集合中的对象
* @Author yangshuai11
* @Date 2022.11.10
*/
public static Long zRemove(String key, Object... value) {
try {
return redisTemplate.opsForZSet().remove(key, value);
} catch (Exception e) {
log.error("Redis删除ZSet对象时出错!key:" + key + ";value:" + Arrays.toString(value));
return 0L;
}
}
/**
* @Desc 删除ZSet指定索引范围的元素
* @Author yangshuai11
* @Date 2022.11.10
*/
public static Long zRemoveRange(String key, long startIndex, long endIndex) {
try {
return redisTemplate.opsForZSet().removeRange(key, startIndex, endIndex);
} catch (Exception e) {
log.error("Redis删除ZSet指定索引范围的元素时出错!key:" + key);
return 0L;
}
}
/**
* @Desc ZSet删除指定分数范围内的元素
* @Author yangshuai11
* @Date 2022.11.10
*/
public static Long zRemoveRangeByScore(String key, double startScore, double endScore) {
try {
return redisTemplate.opsForZSet().removeRangeByScore(key, startScore, endScore);
} catch (Exception e) {
log.error("Redis删除ZSet指定索引范围的元素时出错!key:" + key);
return 0L;
}
}
/*******************通用操作*********************/
/**
* @Desc 删除单个key
* @Author yangshuai11
* @Date 2022.11.02
*/
public static Boolean delete(String key) {
try {
return redisTemplate.delete(key);
} catch (Exception e) {
log.error("Redis删除key时出错!key:" + key);
return false;
}
}
/**
* @Desc 删除多个key
* @Author yangshuai11
* @Date 2022.11.02
*/
public static long delete(Collection<String> keys) {
try {
Long ret = redisTemplate.delete(keys);
return ret == null ? 0 : ret;
} catch (Exception e) {
log.error("Redis删除key时出错!keys:" + keys);
return 0;
}
}
/**
* @Desc 指定失效时间,默认时间为秒
* @Author yangshuai11
* @Date 2022.11.02
*/
public static boolean expire(String key, long time) {
try {
if (time > 0) {
redisTemplate.expire(key, time, TimeUnit.SECONDS);
}
return true;
} catch (Exception e) {
log.error("Redis设置失效时间时出错!key:" + key);
return false;
}
}
/**
* @Desc 指定失效时间,指定时间单位
* @Author yangshuai11
* @Date 2022.11.02
*/
public static boolean expire(String key, long time, TimeUnit timeUnit) {
try {
if (time > 0) {
redisTemplate.expire(key, time, timeUnit);
}
return true;
} catch (Exception e) {
log.error("Redis设置失效时间时出错!key:" + key);
return false;
}
}
}
六、调用RedisUtil工具类
@RestController
@RequestMapping("/api/test")
public class TestController {
@GetMapping("/testRedis")
public void testRedis() {
RedisUtil.set("name", "jack");
String name = RedisUtil.get("name");
List<String> nameList = Arrays.asList("小明", "小红");
RedisUtil.set("nameList", nameList);
List<String> nameList1 = RedisUtil.get("nameList");
}
}