技术标签: spring boot java redis
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
spring:
## Redis 配置
redis:
## Redis数据库索引(默认为0)
database: 0
## Redis服务器地址
host: localhost
## Redis服务器连接端口
port: 6379
## Redis服务器连接密码(默认为空)
password: root
jedis:
pool:
## 连接池最大连接数(使用负值表示没有限制)
#spring.redis.pool.max-active=8
max-active: 8
## 连接池最大阻塞等待时间(使用负值表示没有限制)
#spring.redis.pool.max-wait=-1
max-wait: -1
## 连接池中的最大空闲连接
#spring.redis.pool.max-idle=8
max-idle: 8
## 连接池中的最小空闲连接
#spring.redis.pool.min-idle=0
min-idle: 0
## 连接超时时间(毫秒)
timeout: 1200
SpringBoot自动帮我们在容器中生成了一个RedisTemplate和一个StringRedisTemplate。但是,这个RedisTemplate的泛型是<Object,Object>,写代码不方便,需要写好多类型转换的代码;我们需要一个泛型为<String,Object>形式的RedisTemplate。并且,这个RedisTemplate没有设置数据存在Redis时,key及value的序列化方式。
重新配置一个RedisTemplate
package org.example.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.*;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
// 配置连接工厂
template.setConnectionFactory(factory);
//序列化和反序列化redis中的值
Jackson2JsonRedisSerializer jackson = new Jackson2JsonRedisSerializer(Object.class);
//Java对象转换成JSON结构
ObjectMapper objectMapper = new ObjectMapper();
// 指定要序列化的域
objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
// 指定序列化输入的类型
objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson.setObjectMapper(objectMapper);
// 值采用json序列化
template.setValueSerializer(jackson);
//使用StringRedisSerializer来序列化和反序列化redis的key值
template.setKeySerializer(new StringRedisSerializer());
// 设置hash key和value序列化模式
template.setHashKeySerializer(new StringRedisSerializer());
template.setHashValueSerializer(jackson);
template.afterPropertiesSet();
return template;
}
}
直接用RedisTemplate操作Redis,需要很多行代码,因此直接封装好一个RedisUtils,这样写代码更方便点。这个RedisUtils交给Spring容器实例化,使用时直接注解注入。
工具类代码如下:
package org.example.Util;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
@Component
public class RedisUtil {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
//===============缓存相关方法===============
//指定缓存失效时间
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获取过期时间,返回0代表为永久有效
public long getExpire(String key) {
return redisTemplate.getExpire(key, TimeUnit.SECONDS);
}
//===============数据类型为String的相关方法===============
//根据key值获取缓存值
public Object stringGet(String key) {
return key == null ? null : redisTemplate.opsForValue().get(key);
}
//根据key值存入数据类型为String的缓存值
public boolean stringSet(String key, Object value) {
try {
redisTemplate.opsForValue().set(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
//根据key值存入数据类型为String的缓存值并设置时间
public boolean stringSetWithTime(String key, Object value, long time) {
try {
if (time > 0) {
redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
} else {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
//删除缓存
public void stringDelete(String... key) {
if (key != null && key.length > 0) {
if (key.length == 1) {
redisTemplate.delete(key[0]);
} else {
redisTemplate.delete((Collection<String>) CollectionUtils.arrayToList(key));
}
}
}
//===============数据类型为Hash的相关方法===============
//根据key和item获取缓存值
public Object hashGet(String key, String item) {
return redisTemplate.opsForHash().get(key, item);
}
//根据key和item存入数据类型为Hash的缓存值
public boolean hashSet(String key, String item, Object value) {
try {
redisTemplate.opsForHash().put(key, item, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
//根据key和item存入数据类型为Hash的缓存值并设置时间
public boolean hashSetWithTime(String key, String item, Object value, long time) {
try {
redisTemplate.opsForHash().put(key, item, value);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
//删除缓存
public void hashDelete(String key, Object... item) {
redisTemplate.opsForHash().delete(key, item);
}
//===============数据类型为SET的相关方法===============
//根据key值获取缓存值
public Set<Object> setGet(String key) {
try {
return redisTemplate.opsForSet().members(key);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
//根据key值存入数据类型为SET的缓存值
public long setSet(String key, Object... values) {
try {
return redisTemplate.opsForSet().add(key, values);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
//根据key值存入数据类型为SET的缓存值并设置时间
public long setSetWithTime(String key, long time, Object... values) {
try {
Long count = redisTemplate.opsForSet().add(key, values);
if (time > 0) {
expire(key, time);
}
return count;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
//删除缓存
public long setDelete(String key, Object... values) {
try {
Long count = redisTemplate.opsForSet().remove(key, values);
return count;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
//===============数据类型为LIST的相关方法===============
//获取List缓存的内容,从start到end,若从0到-1代表所有值
public List<Object> listGet(String key, long start, long end) {
try {
return redisTemplate.opsForList().range(key, start, end);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
//根据key值存入数据类型为List的缓存值
public boolean listSet(String key, Object value) {
try {
redisTemplate.opsForList().rightPush(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
//根据key值存入数据类型为List的缓存值并设置时间
public boolean listSetWithTime(String key, Object value, long time) {
try {
redisTemplate.opsForList().rightPush(key, value);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
//删除缓存
public long listDelete(String key, long count, Object value) {
try {
Long remove = redisTemplate.opsForList().remove(key, count, value);
return remove;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
}
2019独角兽企业重金招聘Python工程师标准>>> ...
在张祥雨博士与各位同学畅聊Model设计的新视角以及高产论文的独家秘籍后为满足广大同学的需求我们将在这个暑期大量放送不同主题的线下Workshop!为你缓解CV焦虑感,斩获CV幸福感!本期...
2019独角兽企业重金招聘Python工程师标准>>> ...
Maven项目对象模型(POM),可以通过一小段描述信息来管理项目的构建,报告和文档的软件项目管理工具。Maven 除了以程序构建能力为特色之外,还提供高级项目管理工具。由于 Maven 的缺省构建规则有较高的可重用性,所以常常用两三行 Maven 构建脚本就可以构建简单的项目。由于 Maven 的面向项目的方法,许多 Apache Jakarta 项目发文时使用 Maven,而且公司项目
出处:https://www.sqlsec.com/Django是一个文档很全的框架,学习的时候老是遇到一些坑,这里就顺便记录一下,以便后面使用,同时也希望本文可以帮助到其他的朋友。开发环境操作系统:macOS Cataline 10.15.3Python:pyenv 安装的 pypy3.6-7.3.0 (PyPy解释器平均比我们平时使用的CPython快4.4倍)Django:Django 3....
天气: 晴朗心情: 高兴坐标旋转数字计算机CORDIC(COordinate Rotation DIgital Computer)算法通过移位和加减运算,递归计算常用函数值,如sin, cos, sinh, cosh。以sin/cos计算为例,可利用正/余弦的和角公式递归进行:cos(a+b) = cos(a)cos(b) – sin(a)sin(b) = cos(a) [cos(b) – tan...
linemod_dataset.py路径 注:下面的路径以duck为例,因此出现的文件为“09”。 root = datasets/linemod/Linemod_preprocessed cls_root = datasets/linemod/Linemod_preprocessed/data/09 meta_file:打开datasets/linemod/Linemod_preprocessed/data/09/gt.yml meta_list:加载gt.yml文
2019独角兽企业重金招聘Python工程师标准>>> ...
veridata实验例(3)验证veridata发现insert操作不会导致同步续接:《veridata实验举例(2)验证表BONUS与表SALGRADE两节点同步情况》,地址:点击打开链接环境:ItemSource SystemTarget SystemPlatformRed Ha...
点击上方“蓝字”关注我们9月,秋招如期而至。应届毕业生们,做好准备了吗?是不是为了工作辗转失眠?是不是初入职场焦虑不知所措?是不是为了简历愁秃了头?……在找工作,应聘大厂前,如果仅用关键词...
点击上方“蓝色字”可关注我们!作者:Maggie五、稳定数字货币的风险1.各国央行的数字货币计划的竞争风险区块链技术与数字货币市场的繁荣发展也引起了各国央行的关注,包括中...
在Linux系统中,有许多命令可用于查询主机的硬件信息。一些命令只针对特定的硬件组件,比如CPU、内存,一些命令可以查询多个硬件信息。这篇文章只是简单的让每个人了解查询硬件信息的基本命令使用,包括lscpu、hwinfo、lshw、lspci、lsblk、lsusb等等。1. lscpu用于查询CPU信息?1234