完整版配置(pom.xml)
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.8.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.microStationCom</groupId>
<artifactId>WebApi</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>WebApi</name>
<!-- springboot 打war包。 默认打包方式为 jar , 这里修改为war -->
<!-- <packaging>war</packaging>-->
<!-- -->
<packaging>jar</packaging>
<description>microStationCom WebApi</description>
<properties>
<java.version>1.8</java.version>
<tencent.qcloudsms.version>3.1.298</tencent.qcloudsms.version>
<pagehelper.version>5.0.3</pagehelper.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<!--最终打成war包,排除内置的tomcat
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
-->
</dependency>
<!-- reids -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<!-- 不依赖Redis的异步客户端lettuce -->
<exclusions>
<exclusion>
<groupId>io.lettuce</groupId>
<artifactId>lettuce-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- Jedis客户端依赖,默认版本: jedis = 2.9.3 , commons-pool2 = 2.6.2 -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.3</version>
</dependency>
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>sqljdbc4</artifactId>
<version>4.0</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.9</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- mybatis plus 代码生成器 -->
<!--mybatis plus-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.4.0</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.0</version>
</dependency>
<!--MyBatis的PageHelper插件-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>${pagehelper.version}</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.28</version>
</dependency>
<dependency>
<groupId>com.github.davidfantasy</groupId>
<artifactId>mybatis-plus-generator-ui</artifactId>
<version>1.4.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
<scope>runtime</scope>
</dependency>
<!-- swagger -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<!-- 使用httpclient需要的maven依赖 -->
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpcore -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.9</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.6</version>
</dependency>
<!-- logging日志 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</dependency>
<!--添加servlet-api的依赖,用来打war包 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<scope>provided</scope>
</dependency>
<!-- jstl -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- 引入JWT -->
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.4.1</version>
</dependency>
<!-- 腾讯云短信功能 -->
<dependency>
<groupId>com.tencentcloudapi</groupId>
<artifactId>tencentcloud-sdk-java</artifactId>
<version>3.1.298</version>
</dependency>
<dependency>
<groupId>com.github.qcloudsms</groupId>
<artifactId>qcloudsms</artifactId>
<version>1.0.6</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<fork>false</fork>
</configuration>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<releases>
<enabled>false</enabled>
</releases>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
<pluginRepository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<releases>
<enabled>false</enabled>
</releases>
</pluginRepository>
</pluginRepositories>
</project>
application.properties
# 使用配置文件
spring.profiles.active=dev
#调试模式
# 1、在application.properties文件添加 debug=true
# 2、
debug=true
# Redis 配置
spring.redis.database=0
spring.redis.host=192.168.0.198
spring.redis.port=6379
spring.redis.password=123456
spring.redis.timeout=6000
spring.redis.jedis.pool.min-idle=20
# 最大空闲数,数据库连接的最大空闲时间。超过空闲数量,数据库连接将被标记为不可用,然后被释放。设为0表示无限制
spring.redis.jedis.pool.max-idle=100
##jedis的最大活跃连接数设为0表示无限制
spring.redis.jedis.pool.max-active=500
#最大等待时间:单位ms
#jedis池没有连接对象返回时,等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时。
#如果超过等待时间,则直接抛出JedisConnectionException
spring.redis.jedis.pool.max-wait=60000
Redis配置类: JedisConfig.java
package com.microStationCom.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.cache.annotation.CachingConfigurerSupport;
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;
import org.springframework.util.StringUtils;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
/**
* redis配置类
*/
@Configuration
public class JedisConfig extends CachingConfigurerSupport {
private static Logger logger = LoggerFactory.getLogger(JedisConfig.class);
/**
* SpringSession 需要注意的就是redis需要2.8以上版本,然后开启事件通知,在redis配置文件里面加上
* notify-keyspace-events Ex
* Keyspace notifications功能默认是关闭的(默认地,Keyspace 时间通知功能是禁用的,因为它或多或少会使用一些CPU的资源)。
* 或是使用如下命令:
* redis-cli config set notify-keyspace-events Egx
* 如果你的Redis不是你自己维护的,比如你是使用阿里云的Redis数据库,你不能够更改它的配置,那么可以使用如下方法:在applicationContext.xml中配置
* <util:constant static-field="org.springframework.session.data.redis.config.ConfigureRedisAction.NO_OP"/>
*
* @return
*/
@Value("${spring.redis.host}")
private String host;
@Value("${spring.redis.port}")
private int port;
@Value("${spring.redis.timeout}")
private int timeout;
@Value("${spring.redis.jedis.pool.max-active}")
private int maxActive;
@Value("${spring.redis.jedis.pool.max-idle}")
private int maxIdle;
@Value("${spring.redis.jedis.pool.min-idle}")
private int minIdle;
@Value("${spring.redis.jedis.pool.max-wait}")
private long maxWaitMillis;
@Value("${spring.redis.password}")
private String password;
@Bean
public JedisPool redisPoolFactory() {
logger.info("============== JedisPool 连接池注入 开始 ===============");
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
jedisPoolConfig.setMaxIdle(maxIdle);
jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);
jedisPoolConfig.setMaxTotal(maxActive);
jedisPoolConfig.setMinIdle(minIdle);
JedisPool jedisPool = null;
if (StringUtils.isEmpty(password)) {
jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout);
} else {
jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout, password);
}
logger.info("JedisPool 连接池注入成功");
logger.info("redis连接信息 地址:" + host + ":" + port + ":" + password);
logger.info("============== JedisPool 连接池注入 结束 ===============");
return jedisPool;
}
/**
* retemplate相关配置
* @param factory
* @return
*/
@Bean
public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory factory){
StringRedisTemplate template = new StringRedisTemplate();
// 配置连接工厂
template.setConnectionFactory(factory);
//使用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);
// 值采用json序列化
template.setValueSerializer(new StringRedisSerializer());
//使用StringRedisSerializer来序列化和反序列化redis的key值
template.setKeySerializer(new StringRedisSerializer());
// 设置hash key 和value序列化模式
template.setHashKeySerializer(new StringRedisSerializer());
template.setHashValueSerializer(jacksonSeial);
template.afterPropertiesSet();
return template;
}
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
// 配置连接工厂
template.setConnectionFactory(factory);
//使用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);
// 值采用json序列化
template.setValueSerializer(new StringRedisSerializer());
//使用StringRedisSerializer来序列化和反序列化redis的key值
template.setKeySerializer(new StringRedisSerializer());
// 设置hash key 和value序列化模式
template.setHashKeySerializer(new StringRedisSerializer());
template.setHashValueSerializer(jacksonSeial);
template.afterPropertiesSet();
return template;
}
/**
* 对hash类型的数据操作
*
* @param redisTemplate
* @return
*/
@Bean
public HashOperations<String, String, Object> hashOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForHash();
}
/**
* 对redis字符串类型数据操作
*
* @param redisTemplate
* @return
*/
@Bean
public ValueOperations<String, Object> valueOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForValue();
}
/**
* 对链表类型的数据操作
*
* @param redisTemplate
* @return
*/
@Bean
public ListOperations<String, Object> listOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForList();
}
/**
* 对无序集合类型的数据操作
*
* @param redisTemplate
* @return
*/
@Bean
public SetOperations<String, Object> setOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForSet();
}
/**
* 对有序集合类型的数据操作
*
* @param redisTemplate
* @return
*/
@Bean
public ZSetOperations<String, Object> zSetOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForZSet();
}
}
Redis缓存工具类: RedisCacheUtils.java
package com.microStationCom.util;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import javax.annotation.PostConstruct;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* Redis 缓存工具类
*/
@Component
public class RedisCacheUtils {
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Autowired
private RedisTemplate redisTemplate;
public static StringRedisTemplate stringRedisTemplate1;
public static RedisTemplate redisTemplate1;
//单位警情数据前缀
public static final String KEY_ALARM_GROUPID_PREFIX = "alarmWz:groupId_";
//redis中key的超时时间
public static final long KEY_ALARM_TIMEOUT = 12 * 60 * 60;//单位为秒,2小时(7200秒)
// /** redis操作模板,面向对象的模板 */
// private static StringRedisTemplate stringRedisTemplate
// = (StringRedisTemplate) SpringUtil.getBean("stringRedisTemplate");
// private static RedisTemplate<String, Object> redisTemplate
// = (RedisTemplate) SpringUtil.getBean("redisTemplate");
/**
* 删除缓存<br>
* 根据key精确匹配删除
*
* @param key
*/
@SuppressWarnings("unchecked")
public static void del(String... key) {
if (key != null && key.length > 0) {
if (key.length == 1) {
redisTemplate1.delete(key[0]);
} else {
redisTemplate1.delete(CollectionUtils.arrayToList(key));
}
}
}
/**
* (根据key精确匹配删除)
* @param key
*/
public static void deleteByKey(String key) {
if (key != null) {
if (stringRedisTemplate1.delete(key) == true)
{
}else{
redisTemplate1.delete(key);
}
}
}
/**
* 批量删除<br>
* (该操作会执行模糊查询,请尽量不要使用,以免影响性能或误删)
*
* @param pattern
*/
public void batchDel(String... pattern) {
for (String kp : pattern) {
redisTemplate1.delete(redisTemplate1.keys(kp + "*"));
}
}
/**
* 取得缓存(int型)
*
* @param key
* @return
*/
public Integer getInt(String key) {
String value = stringRedisTemplate1.boundValueOps(key).get();
if (StringUtils.isNotEmpty(value)) {
return Integer.valueOf(value);
}
return null;
}
/**
* 取得缓存(字符串类型)
*
* @param key
* @return
*/
public static String getStr(String key) {
return stringRedisTemplate1.boundValueOps(key).get();
}
/**
* 取得缓存(字符串类型)
*
* @param key
* @return
*/
public static String getStr(String key, boolean retain) {
String value = stringRedisTemplate1.boundValueOps(key).get();
if (!retain) {
redisTemplate1.delete(key);
}
return value;
}
/**
* 模糊查询(根据规则) 返回 keys
* @param pattern
* @return
*/
public static Set<String> searchKeys(String pattern){
return stringRedisTemplate1.keys(pattern);
}
/**
* 获取缓存<br>
* 注:基本数据类型(Character除外),请直接使用get(String key, Class<T> clazz)取值
*
* @param key
* @return
*/
public static Object getObj(String key) {
return redisTemplate1.boundValueOps(key).get();
}
/**
* 获取缓存<br>
* 注:java 8种基本类型的数据请直接使用get(String key, Class<T> clazz)取值
*
* @param key
* @param retain
* 是否保留
* @return
*/
public Object getObj(String key, boolean retain) {
Object obj = redisTemplate1.boundValueOps(key).get();
if (!retain) {
redisTemplate.delete(key);
}
return obj;
}
/**
* 获取缓存<br>
* 注:该方法暂不支持Character数据类型
*
* @param key
* key
* @param clazz
* 类型
* @return
*/
@SuppressWarnings("unchecked")
public <T> T get(String key, Class<T> clazz) {
return (T) redisTemplate1.boundValueOps(key).get();
}
/**
* 获取缓存json对象<br>
*
* @param key
* key
* @param clazz
* 类型
* @return
* @throws Exception
@SuppressWarnings("unchecked")
public <T> T getJson(String key, Class<T> clazz) throws Exception {
String jsonStr=null;
jsonStr=stringRedisTemplate.boundValueOps(key).get();
if(jsonStr==null){
return null;
}else{
return (T) JsonUtil.jsonToBean(jsonStr, clazz);
}
} */
/**
* 将value对象写入缓存
*
* @param key
* @param value
* @param time
* 失效时间(秒)
*/
public static void set(String key, Object value, Long time) {
if (value.getClass().equals(String.class)) {
stringRedisTemplate1.opsForValue().set(key, value.toString());
} else if (value.getClass().equals(Integer.class)) {
stringRedisTemplate1.opsForValue().set(key, value.toString());
} else if (value.getClass().equals(Double.class)) {
stringRedisTemplate1.opsForValue().set(key, value.toString());
} else if (value.getClass().equals(Float.class)) {
stringRedisTemplate1.opsForValue().set(key, value.toString());
} else if (value.getClass().equals(Short.class)) {
stringRedisTemplate1.opsForValue().set(key, value.toString());
} else if (value.getClass().equals(Long.class)) {
stringRedisTemplate1.opsForValue().set(key, value.toString());
} else if (value.getClass().equals(Boolean.class)) {
stringRedisTemplate1.opsForValue().set(key, value.toString());
}
else {
redisTemplate1.opsForValue().set(key, value);
}
if (time != null && time > 0) {
redisTemplate1.expire(key, time, TimeUnit.SECONDS);
stringRedisTemplate1.expire(key, time, TimeUnit.SECONDS);
}
}
/**
* 将value对象以JSON格式写入缓存
*
* @param key
* @param value
* @param time
* 失效时间(秒)
public void setJson(String key, Object value, Long time) {
stringRedisTemplate.opsForValue().set(key, JsonUtil.toJsonString(value));
if (time!=null&&time > 0) {
stringRedisTemplate.expire(key, time, TimeUnit.SECONDS);
}
}
*/
/**
* 更新key对象field的值
*
* @param key
* 缓存key
* @param field
* 缓存对象field
* @param value
* 缓存对象field值
public void setJsonField(String key, String field, String value) {
JSONObject obj = JSON.parseObject(stringRedisTemplate.boundValueOps(key).get());
obj.put(field, value);
stringRedisTemplate.opsForValue().set(key, obj.toJSONString());
}
*/
/**
* 递减操作
*
* @param key
* @param by
* @return
*/
public double decr(String key, double by) {
return redisTemplate1.opsForValue().increment(key, -by);
}
/**
* 递增操作
*
* @param key
* @param by
* @return
*/
public double incr(String key, double by) {
return redisTemplate1.opsForValue().increment(key, by);
}
/**
* 获取double类型值
*
* @param key
* @return
*/
public double getDouble(String key) {
String value = stringRedisTemplate.boundValueOps(key).get();
if (StringUtils.isNotBlank(value)) {
return Double.valueOf(value);
}
return 0d;
}
/**
* 设置double类型值
*
* @param key
* @param value
* @param time
* 失效时间(秒)
*/
public void setDouble(String key, double value, Long time) {
stringRedisTemplate1.opsForValue().set(key, String.valueOf(value));
if (time!=null&&time > 0) {
stringRedisTemplate1.expire(key, time, TimeUnit.SECONDS);
}
}
/**
* 设置double类型值
*
* @param key
* @param value
* @param time
* 失效时间(秒)
*/
public void setInt(String key, int value, Long time) {
stringRedisTemplate1.opsForValue().set(key, String.valueOf(value));
if (time!=null&&time > 0) {
stringRedisTemplate1.expire(key, time, TimeUnit.SECONDS);
}
}
/**
* 将map写入缓存
*
* @param key
* @param map
* @param time
* 失效时间(秒)
*/
public <T> void setMap(String key, Map<String, T> map, Long time) {
redisTemplate1.opsForHash().putAll(key, map);
}
/**
* 将map写入缓存
*
* @param key
* @param map
* @param time
* 失效时间(秒)
@SuppressWarnings("unchecked")
public <T> void setMap(String key, T obj, Long time) {
Map<String, String> map = (Map<String, String>)JsonUtil.parseObject(obj, Map.class);
redisTemplate.opsForHash().putAll(key, map);
}
*/
/**
* 向key对应的map中添加缓存对象
*
* @param key
* @param map
*/
public <T> void addMap(String key, Map<String, T> map) {
redisTemplate1.opsForHash().putAll(key, map);
}
/**
* 向key对应的map中添加缓存对象
*
* @param key
* cache对象key
* @param field
* map对应的key
* @param value
* 值
*/
public void addMap(String key, String field, String value) {
redisTemplate1.opsForHash().put(key, field, value);
}
/**
* 向key对应的map中添加缓存对象
*
* @param key
* cache对象key
* @param field
* map对应的key
* @param obj
* 对象
*/
public <T> void addMap(String key, String field, T obj) {
redisTemplate1.opsForHash().put(key, field, obj);
}
/**
* 获取map缓存
*
* @param key
* @param clazz
* @return
public <T> Map<String, T> mget(String key, Class<T> clazz) {
BoundHashOperations<String, String, T> boundHashOperations = redisTemplate.boundHashOps(key);
return boundHashOperations.entries();
}*/
/**
* 获取map缓存中的某个对象
*
* @param key
* @param field
* @param clazz
* @return
*/
@SuppressWarnings("unchecked")
public <T> T getMapField(String key, String field, Class<T> clazz) {
return (T) redisTemplate1.boundHashOps(key).get(field);
}
/**
* 获取map缓存
*
* @param key
* @param clazz
* @return
public <T> T getMap(String key, Class<T> clazz) {
BoundHashOperations<String, String, String> boundHashOperations = redisTemplate.boundHashOps(key);
Map<String, String> map = boundHashOperations.entries();
return JsonUtil.parseObject(map, clazz);
} */
/**
* 删除map中的某个对象
*
* @author lh
* @date 2016年8月10日
* @param key
* map对应的key
* @param field
* map中该对象的key
*/
public void delMapField(String key, String... field) {
BoundHashOperations<String, String, ?> boundHashOperations = redisTemplate1.boundHashOps(key);
boundHashOperations.delete(field);
}
/**
* 指定缓存的失效时间
*
* @author FangJun
* @date 2016年8月14日
* @param key
* 缓存KEY
* @param time
* 失效时间(秒)
*/
public void expire(String key, Long time) {
if (time!=null&&time > 0) {
redisTemplate1.expire(key, time, TimeUnit.SECONDS);
}
}
/**
* 添加set
*
* @param key
* @param value
*/
public void sadd(String key, String... value) {
redisTemplate1.boundSetOps(key).add(value);
}
/**
* 删除set集合中的对象
*
* @param key
* @param value
*/
public void srem(String key, String... value) {
redisTemplate1.boundSetOps(key).remove(value);
}
/**
* set重命名
*
* @param oldkey
* @param newkey
*/
public void srename(String oldkey, String newkey) {
redisTemplate1.boundSetOps(oldkey).rename(newkey);
}
/**
* 短信缓存
*
* @author fxl
* @date 2016年9月11日
* @param key
* @param value
* @param time
public void setIntForPhone(String key, Object value, int time) {
stringRedisTemplate.opsForValue().set(key, JsonUtil.toJsonString(value));
if (time > 0) {
stringRedisTemplate.expire(key, time, TimeUnit.SECONDS);
}
}
*/
/**
* 模糊查询keys
*
* @param pattern
* @return
*/
public static Set<String> keys(String pattern) {
return redisTemplate1.keys(pattern);
}
/**
*
* @Description (检查key是否存在,返回boolean值 )
* @author feizhou
* @Date 2018年5月29日下午5:37:40
* @version 1.0.0
* @param key
* @return
*/
public Boolean ishasKey(String key) {
return stringRedisTemplate.hasKey(key);
}
@PostConstruct
public StringRedisTemplate getStringRedisTemplate() {
stringRedisTemplate1 = stringRedisTemplate;
System.out.println("获取缓存: getStringRedisTemplate ... " + stringRedisTemplate.toString());
return stringRedisTemplate1;
}
public void setStringRedisTemplate(StringRedisTemplate stringRedisTemplate) {
System.out.println("设置缓存: setStringRedisTemplate ... " + stringRedisTemplate.toString());
this.stringRedisTemplate = stringRedisTemplate;
}
@PostConstruct
public RedisTemplate<String, Object> getRedisTemplate() {
redisTemplate1 = redisTemplate;
System.out.println("获取缓存: getStringRedisTemplate ... " + stringRedisTemplate.toString());
return redisTemplate1;
}
public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
System.out.println("设置缓存: setRedisTemplate ... " + redisTemplate.toString());
this.redisTemplate = redisTemplate;
}
}
//操作redis,直接在控制器类或工具类中,使用 RedisCacheUtils.java类并调用相关的静态方法。
//从redis缓存中取警情信息,条件:需要unitUid
//操作redis
String key = RedisCacheUtils.KEY_ALARM_GROUPID_PREFIX + unitUid;
String alarmDataStr = RedisCacheUtils.getStr(key);
if (!StringUtils.isEmpty(alarmDataStr)){
logger.info("警情信息确认(小程序):alarmId-{}, deptId-{}, groupNo-{}, unitUid-{} ", alarmId , deptId , groupNo , unitUid);
List<AlarmData> list = JSONArray.parseArray(alarmDataStr , AlarmData.class);
//List<AlarmData> list = JSONObject.parseObject(alarmDataStr , List.class);
if (null != list && list.size() > 0){
//更新警情车辆调派记录(小程序):确认时间 2022-08-12
AlarmData alarmData = list.get(0);
int saveFlag = alarmFlowbakService.saveAlarmCarFlowQrsj(alarmData.getUpid() , unitUid);
logger.info("警情信息确认(小程序):更新调派车辆记录确认时间 , 更新标记:{} , upid:{} , unitUid:{} ... " , saveFlag , alarmData.getUpid() , unitUid );
RedisCacheUtils.deleteByKey(key);
logger.info("警情信息确认(小程序):从 Redis 缓存中清除警情信息 ... {} " , alarmDataStr);
}else{
logger.error("警情信息确认(小程序):从 Redis 缓存中读取警情信息出现错误!!! {} " , alarmDataStr);
return JsonUtils.JsonException("确认警情信息出现错误,请联系管理员");
}
}
其他资料
SpringBoot整合Redishttps://blog.csdn.net/hello_list/article/details/124893755Jedis连接工具 和 SpringBoot整合Redis
https://www.cnblogs.com/zxhbk/p/13054709.html