• Redis在SpringBoot项目中使用


    完整版配置(pom.xml)

    1. "1.0" encoding="UTF-8"?>
    2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    4. <modelVersion>4.0.0modelVersion>
    5. <parent>
    6. <groupId>org.springframework.bootgroupId>
    7. <artifactId>spring-boot-starter-parentartifactId>
    8. <version>2.1.8.RELEASEversion>
    9. <relativePath/>
    10. parent>
    11. <groupId>com.microStationComgroupId>
    12. <artifactId>WebApiartifactId>
    13. <version>0.0.1-SNAPSHOTversion>
    14. <name>WebApiname>
    15. <packaging>jarpackaging>
    16. <description>microStationCom WebApidescription>
    17. <properties>
    18. <java.version>1.8java.version>
    19. <tencent.qcloudsms.version>3.1.298tencent.qcloudsms.version>
    20. <pagehelper.version>5.0.3pagehelper.version>
    21. properties>
    22. <dependencies>
    23. <dependency>
    24. <groupId>org.springframework.bootgroupId>
    25. <artifactId>spring-boot-starter-webartifactId>
    26. dependency>
    27. <dependency>
    28. <groupId>org.springframework.bootgroupId>
    29. <artifactId>spring-boot-starter-data-redisartifactId>
    30. <exclusions>
    31. <exclusion>
    32. <groupId>io.lettucegroupId>
    33. <artifactId>lettuce-coreartifactId>
    34. exclusion>
    35. exclusions>
    36. dependency>
    37. <dependency>
    38. <groupId>redis.clientsgroupId>
    39. <artifactId>jedisartifactId>
    40. dependency>
    41. <dependency>
    42. <groupId>org.apache.commonsgroupId>
    43. <artifactId>commons-pool2artifactId>
    44. dependency>
    45. <dependency>
    46. <groupId>commons-langgroupId>
    47. <artifactId>commons-langartifactId>
    48. <version>2.3version>
    49. dependency>
    50. <dependency>
    51. <groupId>com.microsoft.sqlservergroupId>
    52. <artifactId>sqljdbc4artifactId>
    53. <version>4.0version>
    54. <scope>runtimescope>
    55. dependency>
    56. <dependency>
    57. <groupId>com.alibabagroupId>
    58. <artifactId>druid-spring-boot-starterartifactId>
    59. <version>1.1.10version>
    60. dependency>
    61. <dependency>
    62. <groupId>ch.qos.logbackgroupId>
    63. <artifactId>logback-coreartifactId>
    64. dependency>
    65. <dependency>
    66. <groupId>commons-codecgroupId>
    67. <artifactId>commons-codecartifactId>
    68. <version>1.9version>
    69. dependency>
    70. <dependency>
    71. <groupId>org.springframework.bootgroupId>
    72. <artifactId>spring-boot-starter-testartifactId>
    73. <scope>testscope>
    74. dependency>
    75. <dependency>
    76. <groupId>org.projectlombokgroupId>
    77. <artifactId>lombokartifactId>
    78. <optional>trueoptional>
    79. dependency>
    80. <dependency>
    81. <groupId>com.baomidougroupId>
    82. <artifactId>mybatis-plus-generatorartifactId>
    83. <version>3.4.0version>
    84. dependency>
    85. <dependency>
    86. <groupId>com.baomidougroupId>
    87. <artifactId>mybatis-plus-boot-starterartifactId>
    88. <version>3.4.0version>
    89. dependency>
    90. <dependency>
    91. <groupId>com.github.pagehelpergroupId>
    92. <artifactId>pagehelperartifactId>
    93. <version>${pagehelper.version}version>
    94. dependency>
    95. <dependency>
    96. <groupId>com.baomidougroupId>
    97. <artifactId>dynamic-datasource-spring-boot-starterartifactId>
    98. <version>3.1.0version>
    99. dependency>
    100. <dependency>
    101. <groupId>org.freemarkergroupId>
    102. <artifactId>freemarkerartifactId>
    103. <version>2.3.28version>
    104. dependency>
    105. <dependency>
    106. <groupId>com.github.davidfantasygroupId>
    107. <artifactId>mybatis-plus-generator-uiartifactId>
    108. <version>1.4.5version>
    109. <scope>testscope>
    110. dependency>
    111. <dependency>
    112. <groupId>com.alibabagroupId>
    113. <artifactId>fastjsonartifactId>
    114. <version>1.2.47version>
    115. dependency>
    116. <dependency>
    117. <groupId>org.springframework.bootgroupId>
    118. <artifactId>spring-boot-devtoolsartifactId>
    119. <optional>trueoptional>
    120. <scope>runtimescope>
    121. dependency>
    122. <dependency>
    123. <groupId>io.springfoxgroupId>
    124. <artifactId>springfox-swagger2artifactId>
    125. <version>2.9.2version>
    126. dependency>
    127. <dependency>
    128. <groupId>io.springfoxgroupId>
    129. <artifactId>springfox-swagger-uiartifactId>
    130. <version>2.9.2version>
    131. dependency>
    132. <dependency>
    133. <groupId>org.apache.httpcomponentsgroupId>
    134. <artifactId>httpcoreartifactId>
    135. <version>4.4.9version>
    136. dependency>
    137. <dependency>
    138. <groupId>org.apache.httpcomponentsgroupId>
    139. <artifactId>httpclientartifactId>
    140. <version>4.5.6version>
    141. dependency>
    142. <dependency>
    143. <groupId>org.springframework.bootgroupId>
    144. <artifactId>spring-boot-starter-loggingartifactId>
    145. dependency>
    146. <dependency>
    147. <groupId>javax.servletgroupId>
    148. <artifactId>javax.servlet-apiartifactId>
    149. <scope>providedscope>
    150. dependency>
    151. <dependency>
    152. <groupId>jstlgroupId>
    153. <artifactId>jstlartifactId>
    154. <version>1.2version>
    155. dependency>
    156. <dependency>
    157. <groupId>com.auth0groupId>
    158. <artifactId>java-jwtartifactId>
    159. <version>3.4.1version>
    160. dependency>
    161. <dependency>
    162. <groupId>com.tencentcloudapigroupId>
    163. <artifactId>tencentcloud-sdk-javaartifactId>
    164. <version>3.1.298version>
    165. dependency>
    166. <dependency>
    167. <groupId>com.github.qcloudsmsgroupId>
    168. <artifactId>qcloudsmsartifactId>
    169. <version>1.0.6version>
    170. dependency>
    171. dependencies>
    172. <build>
    173. <plugins>
    174. <plugin>
    175. <groupId>org.springframework.bootgroupId>
    176. <artifactId>spring-boot-maven-pluginartifactId>
    177. <configuration>
    178. <fork>falsefork>
    179. configuration>
    180. plugin>
    181. plugins>
    182. build>
    183. <repositories>
    184. <repository>
    185. <id>spring-milestonesid>
    186. <name>Spring Milestonesname>
    187. <url>https://repo.spring.io/milestoneurl>
    188. <snapshots>
    189. <enabled>falseenabled>
    190. snapshots>
    191. repository>
    192. <repository>
    193. <id>spring-snapshotsid>
    194. <name>Spring Snapshotsname>
    195. <url>https://repo.spring.io/snapshoturl>
    196. <releases>
    197. <enabled>falseenabled>
    198. releases>
    199. repository>
    200. repositories>
    201. <pluginRepositories>
    202. <pluginRepository>
    203. <id>spring-milestonesid>
    204. <name>Spring Milestonesname>
    205. <url>https://repo.spring.io/milestoneurl>
    206. <snapshots>
    207. <enabled>falseenabled>
    208. snapshots>
    209. pluginRepository>
    210. <pluginRepository>
    211. <id>spring-snapshotsid>
    212. <name>Spring Snapshotsname>
    213. <url>https://repo.spring.io/snapshoturl>
    214. <releases>
    215. <enabled>falseenabled>
    216. releases>
    217. pluginRepository>
    218. pluginRepositories>
    219. project>

    application.properties

    1. # 使用配置文件
    2. spring.profiles.active=dev
    3. #调试模式
    4. # 1、在application.properties文件添加 debug=true
    5. # 2、
    6. debug=true
    7. # Redis 配置
    8. spring.redis.database=0
    9. spring.redis.host=192.168.0.198
    10. spring.redis.port=6379
    11. spring.redis.password=123456
    12. spring.redis.timeout=6000
    13. spring.redis.jedis.pool.min-idle=20
    14. # 最大空闲数,数据库连接的最大空闲时间。超过空闲数量,数据库连接将被标记为不可用,然后被释放。设为0表示无限制
    15. spring.redis.jedis.pool.max-idle=100
    16. ##jedis的最大活跃连接数设为0表示无限制
    17. spring.redis.jedis.pool.max-active=500
    18. #最大等待时间:单位ms
    19. #jedis池没有连接对象返回时,等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时。
    20. #如果超过等待时间,则直接抛出JedisConnectionException
    21. spring.redis.jedis.pool.max-wait=60000
    Redis配置类: JedisConfig.java
    1. package com.microStationCom.config;
    2. import com.fasterxml.jackson.annotation.JsonAutoDetect;
    3. import com.fasterxml.jackson.annotation.PropertyAccessor;
    4. import com.fasterxml.jackson.databind.ObjectMapper;
    5. import org.slf4j.Logger;
    6. import org.slf4j.LoggerFactory;
    7. import org.springframework.beans.factory.annotation.Autowired;
    8. import org.springframework.beans.factory.annotation.Value;
    9. import org.springframework.cache.annotation.CachingConfigurerSupport;
    10. import org.springframework.context.annotation.Bean;
    11. import org.springframework.context.annotation.Configuration;
    12. import org.springframework.data.redis.connection.RedisConnectionFactory;
    13. import org.springframework.data.redis.core.*;
    14. import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
    15. import org.springframework.data.redis.serializer.StringRedisSerializer;
    16. import org.springframework.util.StringUtils;
    17. import redis.clients.jedis.JedisPool;
    18. import redis.clients.jedis.JedisPoolConfig;
    19. /**
    20. * redis配置类
    21. */
    22. @Configuration
    23. public class JedisConfig extends CachingConfigurerSupport {
    24. private static Logger logger = LoggerFactory.getLogger(JedisConfig.class);
    25. /**
    26. * SpringSession 需要注意的就是redis需要2.8以上版本,然后开启事件通知,在redis配置文件里面加上
    27. * notify-keyspace-events Ex
    28. * Keyspace notifications功能默认是关闭的(默认地,Keyspace 时间通知功能是禁用的,因为它或多或少会使用一些CPU的资源)。
    29. * 或是使用如下命令:
    30. * redis-cli config set notify-keyspace-events Egx
    31. * 如果你的Redis不是你自己维护的,比如你是使用阿里云的Redis数据库,你不能够更改它的配置,那么可以使用如下方法:在applicationContext.xml中配置
    32. *
    33. *
    34. * @return
    35. */
    36. @Value("${spring.redis.host}")
    37. private String host;
    38. @Value("${spring.redis.port}")
    39. private int port;
    40. @Value("${spring.redis.timeout}")
    41. private int timeout;
    42. @Value("${spring.redis.jedis.pool.max-active}")
    43. private int maxActive;
    44. @Value("${spring.redis.jedis.pool.max-idle}")
    45. private int maxIdle;
    46. @Value("${spring.redis.jedis.pool.min-idle}")
    47. private int minIdle;
    48. @Value("${spring.redis.jedis.pool.max-wait}")
    49. private long maxWaitMillis;
    50. @Value("${spring.redis.password}")
    51. private String password;
    52. @Bean
    53. public JedisPool redisPoolFactory() {
    54. logger.info("============== JedisPool 连接池注入 开始 ===============");
    55. JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
    56. jedisPoolConfig.setMaxIdle(maxIdle);
    57. jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);
    58. jedisPoolConfig.setMaxTotal(maxActive);
    59. jedisPoolConfig.setMinIdle(minIdle);
    60. JedisPool jedisPool = null;
    61. if (StringUtils.isEmpty(password)) {
    62. jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout);
    63. } else {
    64. jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout, password);
    65. }
    66. logger.info("JedisPool 连接池注入成功");
    67. logger.info("redis连接信息 地址:" + host + ":" + port + ":" + password);
    68. logger.info("============== JedisPool 连接池注入 结束 ===============");
    69. return jedisPool;
    70. }
    71. /**
    72. * retemplate相关配置
    73. * @param factory
    74. * @return
    75. */
    76. @Bean
    77. public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory factory){
    78. StringRedisTemplate template = new StringRedisTemplate();
    79. // 配置连接工厂
    80. template.setConnectionFactory(factory);
    81. //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
    82. Jackson2JsonRedisSerializer jacksonSeial = new Jackson2JsonRedisSerializer(Object.class);
    83. ObjectMapper om = new ObjectMapper();
    84. // 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public
    85. om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
    86. // 指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会跑出异常
    87. om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
    88. jacksonSeial.setObjectMapper(om);
    89. // 值采用json序列化
    90. template.setValueSerializer(new StringRedisSerializer());
    91. //使用StringRedisSerializer来序列化和反序列化redis的key值
    92. template.setKeySerializer(new StringRedisSerializer());
    93. // 设置hash key 和value序列化模式
    94. template.setHashKeySerializer(new StringRedisSerializer());
    95. template.setHashValueSerializer(jacksonSeial);
    96. template.afterPropertiesSet();
    97. return template;
    98. }
    99. @Bean
    100. public RedisTemplate redisTemplate(RedisConnectionFactory factory) {
    101. RedisTemplate template = new RedisTemplate<>();
    102. // 配置连接工厂
    103. template.setConnectionFactory(factory);
    104. //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
    105. Jackson2JsonRedisSerializer jacksonSeial = new Jackson2JsonRedisSerializer(Object.class);
    106. ObjectMapper om = new ObjectMapper();
    107. // 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public
    108. om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
    109. // 指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会跑出异常
    110. om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
    111. jacksonSeial.setObjectMapper(om);
    112. // 值采用json序列化
    113. template.setValueSerializer(new StringRedisSerializer());
    114. //使用StringRedisSerializer来序列化和反序列化redis的key值
    115. template.setKeySerializer(new StringRedisSerializer());
    116. // 设置hash key 和value序列化模式
    117. template.setHashKeySerializer(new StringRedisSerializer());
    118. template.setHashValueSerializer(jacksonSeial);
    119. template.afterPropertiesSet();
    120. return template;
    121. }
    122. /**
    123. * 对hash类型的数据操作
    124. *
    125. * @param redisTemplate
    126. * @return
    127. */
    128. @Bean
    129. public HashOperations hashOperations(RedisTemplate redisTemplate) {
    130. return redisTemplate.opsForHash();
    131. }
    132. /**
    133. * 对redis字符串类型数据操作
    134. *
    135. * @param redisTemplate
    136. * @return
    137. */
    138. @Bean
    139. public ValueOperations valueOperations(RedisTemplate redisTemplate) {
    140. return redisTemplate.opsForValue();
    141. }
    142. /**
    143. * 对链表类型的数据操作
    144. *
    145. * @param redisTemplate
    146. * @return
    147. */
    148. @Bean
    149. public ListOperations listOperations(RedisTemplate redisTemplate) {
    150. return redisTemplate.opsForList();
    151. }
    152. /**
    153. * 对无序集合类型的数据操作
    154. *
    155. * @param redisTemplate
    156. * @return
    157. */
    158. @Bean
    159. public SetOperations setOperations(RedisTemplate redisTemplate) {
    160. return redisTemplate.opsForSet();
    161. }
    162. /**
    163. * 对有序集合类型的数据操作
    164. *
    165. * @param redisTemplate
    166. * @return
    167. */
    168. @Bean
    169. public ZSetOperations zSetOperations(RedisTemplate redisTemplate) {
    170. return redisTemplate.opsForZSet();
    171. }
    172. }
    Redis缓存工具类: RedisCacheUtils.java
    1. package com.microStationCom.util;
    2. import org.apache.commons.lang.StringUtils;
    3. import org.springframework.beans.factory.annotation.Autowired;
    4. import org.springframework.data.redis.core.BoundHashOperations;
    5. import org.springframework.data.redis.core.RedisTemplate;
    6. import org.springframework.data.redis.core.StringRedisTemplate;
    7. import org.springframework.stereotype.Component;
    8. import org.springframework.util.CollectionUtils;
    9. import javax.annotation.PostConstruct;
    10. import java.util.Map;
    11. import java.util.Set;
    12. import java.util.concurrent.TimeUnit;
    13. /**
    14. * Redis 缓存工具类
    15. */
    16. @Component
    17. public class RedisCacheUtils {
    18. @Autowired
    19. private StringRedisTemplate stringRedisTemplate;
    20. @Autowired
    21. private RedisTemplate redisTemplate;
    22. public static StringRedisTemplate stringRedisTemplate1;
    23. public static RedisTemplate redisTemplate1;
    24. //单位警情数据前缀
    25. public static final String KEY_ALARM_GROUPID_PREFIX = "alarmWz:groupId_";
    26. //redis中key的超时时间
    27. public static final long KEY_ALARM_TIMEOUT = 12 * 60 * 60;//单位为秒,2小时(7200秒)
    28. // /** redis操作模板,面向对象的模板 */
    29. // private static StringRedisTemplate stringRedisTemplate
    30. // = (StringRedisTemplate) SpringUtil.getBean("stringRedisTemplate");
    31. // private static RedisTemplate redisTemplate
    32. // = (RedisTemplate) SpringUtil.getBean("redisTemplate");
    33. /**
    34. * 删除缓存
    35. * 根据key精确匹配删除
    36. *
    37. * @param key
    38. */
    39. @SuppressWarnings("unchecked")
    40. public static void del(String... key) {
    41. if (key != null && key.length > 0) {
    42. if (key.length == 1) {
    43. redisTemplate1.delete(key[0]);
    44. } else {
    45. redisTemplate1.delete(CollectionUtils.arrayToList(key));
    46. }
    47. }
    48. }
    49. /**
    50. * (根据key精确匹配删除)
    51. * @param key
    52. */
    53. public static void deleteByKey(String key) {
    54. if (key != null) {
    55. if (stringRedisTemplate1.delete(key) == true)
    56. {
    57. }else{
    58. redisTemplate1.delete(key);
    59. }
    60. }
    61. }
    62. /**
    63. * 批量删除
    64. * (该操作会执行模糊查询,请尽量不要使用,以免影响性能或误删)
    65. *
    66. * @param pattern
    67. */
    68. public void batchDel(String... pattern) {
    69. for (String kp : pattern) {
    70. redisTemplate1.delete(redisTemplate1.keys(kp + "*"));
    71. }
    72. }
    73. /**
    74. * 取得缓存(int型)
    75. *
    76. * @param key
    77. * @return
    78. */
    79. public Integer getInt(String key) {
    80. String value = stringRedisTemplate1.boundValueOps(key).get();
    81. if (StringUtils.isNotEmpty(value)) {
    82. return Integer.valueOf(value);
    83. }
    84. return null;
    85. }
    86. /**
    87. * 取得缓存(字符串类型)
    88. *
    89. * @param key
    90. * @return
    91. */
    92. public static String getStr(String key) {
    93. return stringRedisTemplate1.boundValueOps(key).get();
    94. }
    95. /**
    96. * 取得缓存(字符串类型)
    97. *
    98. * @param key
    99. * @return
    100. */
    101. public static String getStr(String key, boolean retain) {
    102. String value = stringRedisTemplate1.boundValueOps(key).get();
    103. if (!retain) {
    104. redisTemplate1.delete(key);
    105. }
    106. return value;
    107. }
    108. /**
    109. * 模糊查询(根据规则) 返回 keys
    110. * @param pattern
    111. * @return
    112. */
    113. public static Set searchKeys(String pattern){
    114. return stringRedisTemplate1.keys(pattern);
    115. }
    116. /**
    117. * 获取缓存
    118. * 注:基本数据类型(Character除外),请直接使用get(String key, Class clazz)取值
    119. *
    120. * @param key
    121. * @return
    122. */
    123. public static Object getObj(String key) {
    124. return redisTemplate1.boundValueOps(key).get();
    125. }
    126. /**
    127. * 获取缓存
    128. * 注:java 8种基本类型的数据请直接使用get(String key, Class clazz)取值
    129. *
    130. * @param key
    131. * @param retain
    132. * 是否保留
    133. * @return
    134. */
    135. public Object getObj(String key, boolean retain) {
    136. Object obj = redisTemplate1.boundValueOps(key).get();
    137. if (!retain) {
    138. redisTemplate.delete(key);
    139. }
    140. return obj;
    141. }
    142. /**
    143. * 获取缓存
    144. * 注:该方法暂不支持Character数据类型
    145. *
    146. * @param key
    147. * key
    148. * @param clazz
    149. * 类型
    150. * @return
    151. */
    152. @SuppressWarnings("unchecked")
    153. public T get(String key, Class clazz) {
    154. return (T) redisTemplate1.boundValueOps(key).get();
    155. }
    156. /**
    157. * 获取缓存json对象
    158. *
    159. * @param key
    160. * key
    161. * @param clazz
    162. * 类型
    163. * @return
    164. * @throws Exception
    165. @SuppressWarnings("unchecked")
    166. public T getJson(String key, Class clazz) throws Exception {
    167. String jsonStr=null;
    168. jsonStr=stringRedisTemplate.boundValueOps(key).get();
    169. if(jsonStr==null){
    170. return null;
    171. }else{
    172. return (T) JsonUtil.jsonToBean(jsonStr, clazz);
    173. }
    174. } */
    175. /**
    176. * 将value对象写入缓存
    177. *
    178. * @param key
    179. * @param value
    180. * @param time
    181. * 失效时间(秒)
    182. */
    183. public static void set(String key, Object value, Long time) {
    184. if (value.getClass().equals(String.class)) {
    185. stringRedisTemplate1.opsForValue().set(key, value.toString());
    186. } else if (value.getClass().equals(Integer.class)) {
    187. stringRedisTemplate1.opsForValue().set(key, value.toString());
    188. } else if (value.getClass().equals(Double.class)) {
    189. stringRedisTemplate1.opsForValue().set(key, value.toString());
    190. } else if (value.getClass().equals(Float.class)) {
    191. stringRedisTemplate1.opsForValue().set(key, value.toString());
    192. } else if (value.getClass().equals(Short.class)) {
    193. stringRedisTemplate1.opsForValue().set(key, value.toString());
    194. } else if (value.getClass().equals(Long.class)) {
    195. stringRedisTemplate1.opsForValue().set(key, value.toString());
    196. } else if (value.getClass().equals(Boolean.class)) {
    197. stringRedisTemplate1.opsForValue().set(key, value.toString());
    198. }
    199. else {
    200. redisTemplate1.opsForValue().set(key, value);
    201. }
    202. if (time != null && time > 0) {
    203. redisTemplate1.expire(key, time, TimeUnit.SECONDS);
    204. stringRedisTemplate1.expire(key, time, TimeUnit.SECONDS);
    205. }
    206. }
    207. /**
    208. * 将value对象以JSON格式写入缓存
    209. *
    210. * @param key
    211. * @param value
    212. * @param time
    213. * 失效时间(秒)
    214. public void setJson(String key, Object value, Long time) {
    215. stringRedisTemplate.opsForValue().set(key, JsonUtil.toJsonString(value));
    216. if (time!=null&&time > 0) {
    217. stringRedisTemplate.expire(key, time, TimeUnit.SECONDS);
    218. }
    219. }
    220. */
    221. /**
    222. * 更新key对象field的值
    223. *
    224. * @param key
    225. * 缓存key
    226. * @param field
    227. * 缓存对象field
    228. * @param value
    229. * 缓存对象field值
    230. public void setJsonField(String key, String field, String value) {
    231. JSONObject obj = JSON.parseObject(stringRedisTemplate.boundValueOps(key).get());
    232. obj.put(field, value);
    233. stringRedisTemplate.opsForValue().set(key, obj.toJSONString());
    234. }
    235. */
    236. /**
    237. * 递减操作
    238. *
    239. * @param key
    240. * @param by
    241. * @return
    242. */
    243. public double decr(String key, double by) {
    244. return redisTemplate1.opsForValue().increment(key, -by);
    245. }
    246. /**
    247. * 递增操作
    248. *
    249. * @param key
    250. * @param by
    251. * @return
    252. */
    253. public double incr(String key, double by) {
    254. return redisTemplate1.opsForValue().increment(key, by);
    255. }
    256. /**
    257. * 获取double类型值
    258. *
    259. * @param key
    260. * @return
    261. */
    262. public double getDouble(String key) {
    263. String value = stringRedisTemplate.boundValueOps(key).get();
    264. if (StringUtils.isNotBlank(value)) {
    265. return Double.valueOf(value);
    266. }
    267. return 0d;
    268. }
    269. /**
    270. * 设置double类型值
    271. *
    272. * @param key
    273. * @param value
    274. * @param time
    275. * 失效时间(秒)
    276. */
    277. public void setDouble(String key, double value, Long time) {
    278. stringRedisTemplate1.opsForValue().set(key, String.valueOf(value));
    279. if (time!=null&&time > 0) {
    280. stringRedisTemplate1.expire(key, time, TimeUnit.SECONDS);
    281. }
    282. }
    283. /**
    284. * 设置double类型值
    285. *
    286. * @param key
    287. * @param value
    288. * @param time
    289. * 失效时间(秒)
    290. */
    291. public void setInt(String key, int value, Long time) {
    292. stringRedisTemplate1.opsForValue().set(key, String.valueOf(value));
    293. if (time!=null&&time > 0) {
    294. stringRedisTemplate1.expire(key, time, TimeUnit.SECONDS);
    295. }
    296. }
    297. /**
    298. * 将map写入缓存
    299. *
    300. * @param key
    301. * @param map
    302. * @param time
    303. * 失效时间(秒)
    304. */
    305. public void setMap(String key, Map map, Long time) {
    306. redisTemplate1.opsForHash().putAll(key, map);
    307. }
    308. /**
    309. * 将map写入缓存
    310. *
    311. * @param key
    312. * @param map
    313. * @param time
    314. * 失效时间(秒)
    315. @SuppressWarnings("unchecked")
    316. public void setMap(String key, T obj, Long time) {
    317. Map map = (Map)JsonUtil.parseObject(obj, Map.class);
    318. redisTemplate.opsForHash().putAll(key, map);
    319. }
    320. */
    321. /**
    322. * 向key对应的map中添加缓存对象
    323. *
    324. * @param key
    325. * @param map
    326. */
    327. public void addMap(String key, Map map) {
    328. redisTemplate1.opsForHash().putAll(key, map);
    329. }
    330. /**
    331. * 向key对应的map中添加缓存对象
    332. *
    333. * @param key
    334. * cache对象key
    335. * @param field
    336. * map对应的key
    337. * @param value
    338. * 值
    339. */
    340. public void addMap(String key, String field, String value) {
    341. redisTemplate1.opsForHash().put(key, field, value);
    342. }
    343. /**
    344. * 向key对应的map中添加缓存对象
    345. *
    346. * @param key
    347. * cache对象key
    348. * @param field
    349. * map对应的key
    350. * @param obj
    351. * 对象
    352. */
    353. public void addMap(String key, String field, T obj) {
    354. redisTemplate1.opsForHash().put(key, field, obj);
    355. }
    356. /**
    357. * 获取map缓存
    358. *
    359. * @param key
    360. * @param clazz
    361. * @return
    362. public Map mget(String key, Class clazz) {
    363. BoundHashOperations boundHashOperations = redisTemplate.boundHashOps(key);
    364. return boundHashOperations.entries();
    365. }*/
    366. /**
    367. * 获取map缓存中的某个对象
    368. *
    369. * @param key
    370. * @param field
    371. * @param clazz
    372. * @return
    373. */
    374. @SuppressWarnings("unchecked")
    375. public T getMapField(String key, String field, Class clazz) {
    376. return (T) redisTemplate1.boundHashOps(key).get(field);
    377. }
    378. /**
    379. * 获取map缓存
    380. *
    381. * @param key
    382. * @param clazz
    383. * @return
    384. public T getMap(String key, Class clazz) {
    385. BoundHashOperations boundHashOperations = redisTemplate.boundHashOps(key);
    386. Map map = boundHashOperations.entries();
    387. return JsonUtil.parseObject(map, clazz);
    388. } */
    389. /**
    390. * 删除map中的某个对象
    391. *
    392. * @author lh
    393. * @date 2016年8月10日
    394. * @param key
    395. * map对应的key
    396. * @param field
    397. * map中该对象的key
    398. */
    399. public void delMapField(String key, String... field) {
    400. BoundHashOperations boundHashOperations = redisTemplate1.boundHashOps(key);
    401. boundHashOperations.delete(field);
    402. }
    403. /**
    404. * 指定缓存的失效时间
    405. *
    406. * @author FangJun
    407. * @date 2016年8月14日
    408. * @param key
    409. * 缓存KEY
    410. * @param time
    411. * 失效时间(秒)
    412. */
    413. public void expire(String key, Long time) {
    414. if (time!=null&&time > 0) {
    415. redisTemplate1.expire(key, time, TimeUnit.SECONDS);
    416. }
    417. }
    418. /**
    419. * 添加set
    420. *
    421. * @param key
    422. * @param value
    423. */
    424. public void sadd(String key, String... value) {
    425. redisTemplate1.boundSetOps(key).add(value);
    426. }
    427. /**
    428. * 删除set集合中的对象
    429. *
    430. * @param key
    431. * @param value
    432. */
    433. public void srem(String key, String... value) {
    434. redisTemplate1.boundSetOps(key).remove(value);
    435. }
    436. /**
    437. * set重命名
    438. *
    439. * @param oldkey
    440. * @param newkey
    441. */
    442. public void srename(String oldkey, String newkey) {
    443. redisTemplate1.boundSetOps(oldkey).rename(newkey);
    444. }
    445. /**
    446. * 短信缓存
    447. *
    448. * @author fxl
    449. * @date 2016年9月11日
    450. * @param key
    451. * @param value
    452. * @param time
    453. public void setIntForPhone(String key, Object value, int time) {
    454. stringRedisTemplate.opsForValue().set(key, JsonUtil.toJsonString(value));
    455. if (time > 0) {
    456. stringRedisTemplate.expire(key, time, TimeUnit.SECONDS);
    457. }
    458. }
    459. */
    460. /**
    461. * 模糊查询keys
    462. *
    463. * @param pattern
    464. * @return
    465. */
    466. public static Set keys(String pattern) {
    467. return redisTemplate1.keys(pattern);
    468. }
    469. /**
    470. *
    471. * @Description (检查key是否存在,返回boolean值 )
    472. * @author feizhou
    473. * @Date 2018年5月29日下午5:37:40
    474. * @version 1.0.0
    475. * @param key
    476. * @return
    477. */
    478. public Boolean ishasKey(String key) {
    479. return stringRedisTemplate.hasKey(key);
    480. }
    481. @PostConstruct
    482. public StringRedisTemplate getStringRedisTemplate() {
    483. stringRedisTemplate1 = stringRedisTemplate;
    484. System.out.println("获取缓存: getStringRedisTemplate ... " + stringRedisTemplate.toString());
    485. return stringRedisTemplate1;
    486. }
    487. public void setStringRedisTemplate(StringRedisTemplate stringRedisTemplate) {
    488. System.out.println("设置缓存: setStringRedisTemplate ... " + stringRedisTemplate.toString());
    489. this.stringRedisTemplate = stringRedisTemplate;
    490. }
    491. @PostConstruct
    492. public RedisTemplate getRedisTemplate() {
    493. redisTemplate1 = redisTemplate;
    494. System.out.println("获取缓存: getStringRedisTemplate ... " + stringRedisTemplate.toString());
    495. return redisTemplate1;
    496. }
    497. public void setRedisTemplate(RedisTemplate redisTemplate) {
    498. System.out.println("设置缓存: setRedisTemplate ... " + redisTemplate.toString());
    499. this.redisTemplate = redisTemplate;
    500. }
    501. }

    //操作redis,直接在控制器类或工具类中,使用 RedisCacheUtils.java类并调用相关的静态方法。
    1. //从redis缓存中取警情信息,条件:需要unitUid
    2. //操作redis
    3. String key = RedisCacheUtils.KEY_ALARM_GROUPID_PREFIX + unitUid;
    4. String alarmDataStr = RedisCacheUtils.getStr(key);
    5. if (!StringUtils.isEmpty(alarmDataStr)){
    6. logger.info("警情信息确认(小程序):alarmId-{}, deptId-{}, groupNo-{}, unitUid-{} ", alarmId , deptId , groupNo , unitUid);
    7. List list = JSONArray.parseArray(alarmDataStr , AlarmData.class);
    8. //List list = JSONObject.parseObject(alarmDataStr , List.class);
    9. if (null != list && list.size() > 0){
    10. //更新警情车辆调派记录(小程序):确认时间 2022-08-12
    11. AlarmData alarmData = list.get(0);
    12. int saveFlag = alarmFlowbakService.saveAlarmCarFlowQrsj(alarmData.getUpid() , unitUid);
    13. logger.info("警情信息确认(小程序):更新调派车辆记录确认时间 , 更新标记:{} , upid:{} , unitUid:{} ... " , saveFlag , alarmData.getUpid() , unitUid );
    14. RedisCacheUtils.deleteByKey(key);
    15. logger.info("警情信息确认(小程序):从 Redis 缓存中清除警情信息 ... {} " , alarmDataStr);
    16. }else{
    17. logger.error("警情信息确认(小程序):从 Redis 缓存中读取警情信息出现错误!!! {} " , alarmDataStr);
    18. return JsonUtils.JsonException("确认警情信息出现错误,请联系管理员");
    19. }
    20. }


    其他资料

    SpringBoot整合Redisicon-default.png?t=M85Bhttps://blog.csdn.net/hello_list/article/details/124893755Jedis连接工具 和 SpringBoot整合Redisicon-default.png?t=M85Bhttps://www.cnblogs.com/zxhbk/p/13054709.html

  • 相关阅读:
    工程管理系统源码之全面+高效的工程项目管理软件
    从零实现 promise 的 class 和 function 版本
    全国双非院校考研信息汇总整理 Part.3
    在vue3框架中使用vant的input组件安卓端闪退的问题
    MySQL索引详解
    go操作Kfaka
    电脑系统Windows11安全中心内存完整性打开不了怎么办
    vue 使用this.$set设置对象属性值时,不更新试图
    如何基于WPF写一款数据库文档管理工具(二)
    高频数据分析:使用数据透视
  • 原文地址:https://blog.csdn.net/zgphacker2010/article/details/127138048