当前位置:   article > 正文

Redis在SpringBoot项目中使用_stringredisserializer.utf_8

stringredisserializer.utf_8

完整版配置(pom.xml)

  1. <?xml version="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.0</modelVersion>
  5. <parent>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-parent</artifactId>
  8. <version>2.1.8.RELEASE</version>
  9. <relativePath/> <!-- lookup parent from repository -->
  10. </parent>
  11. <groupId>com.microStationCom</groupId>
  12. <artifactId>WebApi</artifactId>
  13. <version>0.0.1-SNAPSHOT</version>
  14. <name>WebApi</name>
  15. <!-- springboot 打war包。 默认打包方式为 jar , 这里修改为war -->
  16. <!-- <packaging>war</packaging>-->
  17. <!-- -->
  18. <packaging>jar</packaging>
  19. <description>microStationCom WebApi</description>
  20. <properties>
  21. <java.version>1.8</java.version>
  22. <tencent.qcloudsms.version>3.1.298</tencent.qcloudsms.version>
  23. <pagehelper.version>5.0.3</pagehelper.version>
  24. </properties>
  25. <dependencies>
  26. <dependency>
  27. <groupId>org.springframework.boot</groupId>
  28. <artifactId>spring-boot-starter-web</artifactId>
  29. <!--最终打成war包,排除内置的tomcat
  30. <exclusions>
  31. <exclusion>
  32. <groupId>org.springframework.boot</groupId>
  33. <artifactId>spring-boot-starter-tomcat</artifactId>
  34. </exclusion>
  35. </exclusions>
  36. -->
  37. </dependency>
  38. <!-- reids -->
  39. <dependency>
  40. <groupId>org.springframework.boot</groupId>
  41. <artifactId>spring-boot-starter-data-redis</artifactId>
  42. <!-- 不依赖Redis的异步客户端lettuce -->
  43. <exclusions>
  44. <exclusion>
  45. <groupId>io.lettuce</groupId>
  46. <artifactId>lettuce-core</artifactId>
  47. </exclusion>
  48. </exclusions>
  49. </dependency>
  50. <!-- Jedis客户端依赖,默认版本: jedis = 2.9.3 , commons-pool2 = 2.6.2 -->
  51. <dependency>
  52. <groupId>redis.clients</groupId>
  53. <artifactId>jedis</artifactId>
  54. </dependency>
  55. <dependency>
  56. <groupId>org.apache.commons</groupId>
  57. <artifactId>commons-pool2</artifactId>
  58. </dependency>
  59. <dependency>
  60. <groupId>commons-lang</groupId>
  61. <artifactId>commons-lang</artifactId>
  62. <version>2.3</version>
  63. </dependency>
  64. <dependency>
  65. <groupId>com.microsoft.sqlserver</groupId>
  66. <artifactId>sqljdbc4</artifactId>
  67. <version>4.0</version>
  68. <scope>runtime</scope>
  69. </dependency>
  70. <dependency>
  71. <groupId>com.alibaba</groupId>
  72. <artifactId>druid-spring-boot-starter</artifactId>
  73. <version>1.1.10</version>
  74. </dependency>
  75. <dependency>
  76. <groupId>ch.qos.logback</groupId>
  77. <artifactId>logback-core</artifactId>
  78. </dependency>
  79. <dependency>
  80. <groupId>commons-codec</groupId>
  81. <artifactId>commons-codec</artifactId>
  82. <version>1.9</version>
  83. </dependency>
  84. <dependency>
  85. <groupId>org.springframework.boot</groupId>
  86. <artifactId>spring-boot-starter-test</artifactId>
  87. <scope>test</scope>
  88. </dependency>
  89. <dependency>
  90. <groupId>org.projectlombok</groupId>
  91. <artifactId>lombok</artifactId>
  92. <optional>true</optional>
  93. </dependency>
  94. <!-- mybatis plus 代码生成器 -->
  95. <!--mybatis plus-->
  96. <dependency>
  97. <groupId>com.baomidou</groupId>
  98. <artifactId>mybatis-plus-generator</artifactId>
  99. <version>3.4.0</version>
  100. </dependency>
  101. <dependency>
  102. <groupId>com.baomidou</groupId>
  103. <artifactId>mybatis-plus-boot-starter</artifactId>
  104. <version>3.4.0</version>
  105. </dependency>
  106. <!--MyBatis的PageHelper插件-->
  107. <dependency>
  108. <groupId>com.github.pagehelper</groupId>
  109. <artifactId>pagehelper</artifactId>
  110. <version>${pagehelper.version}</version>
  111. </dependency>
  112. <dependency>
  113. <groupId>com.baomidou</groupId>
  114. <artifactId>dynamic-datasource-spring-boot-starter</artifactId>
  115. <version>3.1.0</version>
  116. </dependency>
  117. <dependency>
  118. <groupId>org.freemarker</groupId>
  119. <artifactId>freemarker</artifactId>
  120. <version>2.3.28</version>
  121. </dependency>
  122. <dependency>
  123. <groupId>com.github.davidfantasy</groupId>
  124. <artifactId>mybatis-plus-generator-ui</artifactId>
  125. <version>1.4.5</version>
  126. <scope>test</scope>
  127. </dependency>
  128. <dependency>
  129. <groupId>com.alibaba</groupId>
  130. <artifactId>fastjson</artifactId>
  131. <version>1.2.47</version>
  132. </dependency>
  133. <dependency>
  134. <groupId>org.springframework.boot</groupId>
  135. <artifactId>spring-boot-devtools</artifactId>
  136. <optional>true</optional>
  137. <scope>runtime</scope>
  138. </dependency>
  139. <!-- swagger -->
  140. <dependency>
  141. <groupId>io.springfox</groupId>
  142. <artifactId>springfox-swagger2</artifactId>
  143. <version>2.9.2</version>
  144. </dependency>
  145. <dependency>
  146. <groupId>io.springfox</groupId>
  147. <artifactId>springfox-swagger-ui</artifactId>
  148. <version>2.9.2</version>
  149. </dependency>
  150. <!-- 使用httpclient需要的maven依赖 -->
  151. <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpcore -->
  152. <dependency>
  153. <groupId>org.apache.httpcomponents</groupId>
  154. <artifactId>httpcore</artifactId>
  155. <version>4.4.9</version>
  156. </dependency>
  157. <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
  158. <dependency>
  159. <groupId>org.apache.httpcomponents</groupId>
  160. <artifactId>httpclient</artifactId>
  161. <version>4.5.6</version>
  162. </dependency>
  163. <!-- logging日志 -->
  164. <dependency>
  165. <groupId>org.springframework.boot</groupId>
  166. <artifactId>spring-boot-starter-logging</artifactId>
  167. </dependency>
  168. <!--添加servlet-api的依赖,用来打war包 -->
  169. <dependency>
  170. <groupId>javax.servlet</groupId>
  171. <artifactId>javax.servlet-api</artifactId>
  172. <scope>provided</scope>
  173. </dependency>
  174. <!-- jstl -->
  175. <dependency>
  176. <groupId>jstl</groupId>
  177. <artifactId>jstl</artifactId>
  178. <version>1.2</version>
  179. </dependency>
  180. <!-- 引入JWT -->
  181. <dependency>
  182. <groupId>com.auth0</groupId>
  183. <artifactId>java-jwt</artifactId>
  184. <version>3.4.1</version>
  185. </dependency>
  186. <!-- 腾讯云短信功能 -->
  187. <dependency>
  188. <groupId>com.tencentcloudapi</groupId>
  189. <artifactId>tencentcloud-sdk-java</artifactId>
  190. <version>3.1.298</version>
  191. </dependency>
  192. <dependency>
  193. <groupId>com.github.qcloudsms</groupId>
  194. <artifactId>qcloudsms</artifactId>
  195. <version>1.0.6</version>
  196. </dependency>
  197. </dependencies>
  198. <build>
  199. <plugins>
  200. <plugin>
  201. <groupId>org.springframework.boot</groupId>
  202. <artifactId>spring-boot-maven-plugin</artifactId>
  203. <configuration>
  204. <fork>false</fork>
  205. </configuration>
  206. </plugin>
  207. </plugins>
  208. </build>
  209. <repositories>
  210. <repository>
  211. <id>spring-milestones</id>
  212. <name>Spring Milestones</name>
  213. <url>https://repo.spring.io/milestone</url>
  214. <snapshots>
  215. <enabled>false</enabled>
  216. </snapshots>
  217. </repository>
  218. <repository>
  219. <id>spring-snapshots</id>
  220. <name>Spring Snapshots</name>
  221. <url>https://repo.spring.io/snapshot</url>
  222. <releases>
  223. <enabled>false</enabled>
  224. </releases>
  225. </repository>
  226. </repositories>
  227. <pluginRepositories>
  228. <pluginRepository>
  229. <id>spring-milestones</id>
  230. <name>Spring Milestones</name>
  231. <url>https://repo.spring.io/milestone</url>
  232. <snapshots>
  233. <enabled>false</enabled>
  234. </snapshots>
  235. </pluginRepository>
  236. <pluginRepository>
  237. <id>spring-snapshots</id>
  238. <name>Spring Snapshots</name>
  239. <url>https://repo.spring.io/snapshot</url>
  240. <releases>
  241. <enabled>false</enabled>
  242. </releases>
  243. </pluginRepository>
  244. </pluginRepositories>
  245. </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. * <util:constant static-field="org.springframework.session.data.redis.config.ConfigureRedisAction.NO_OP"/>
  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<String, Object> redisTemplate(RedisConnectionFactory factory) {
  101. RedisTemplate<String, Object> 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<String, String, Object> hashOperations(RedisTemplate<String, Object> redisTemplate) {
  130. return redisTemplate.opsForHash();
  131. }
  132. /**
  133. * 对redis字符串类型数据操作
  134. *
  135. * @param redisTemplate
  136. * @return
  137. */
  138. @Bean
  139. public ValueOperations<String, Object> valueOperations(RedisTemplate<String, Object> redisTemplate) {
  140. return redisTemplate.opsForValue();
  141. }
  142. /**
  143. * 对链表类型的数据操作
  144. *
  145. * @param redisTemplate
  146. * @return
  147. */
  148. @Bean
  149. public ListOperations<String, Object> listOperations(RedisTemplate<String, Object> redisTemplate) {
  150. return redisTemplate.opsForList();
  151. }
  152. /**
  153. * 对无序集合类型的数据操作
  154. *
  155. * @param redisTemplate
  156. * @return
  157. */
  158. @Bean
  159. public SetOperations<String, Object> setOperations(RedisTemplate<String, Object> redisTemplate) {
  160. return redisTemplate.opsForSet();
  161. }
  162. /**
  163. * 对有序集合类型的数据操作
  164. *
  165. * @param redisTemplate
  166. * @return
  167. */
  168. @Bean
  169. public ZSetOperations<String, Object> zSetOperations(RedisTemplate<String, Object> 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<String, Object> redisTemplate
  32. // = (RedisTemplate) SpringUtil.getBean("redisTemplate");
  33. /**
  34. * 删除缓存<br>
  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. * 批量删除<br>
  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<String> searchKeys(String pattern){
  114. return stringRedisTemplate1.keys(pattern);
  115. }
  116. /**
  117. * 获取缓存<br>
  118. * 注:基本数据类型(Character除外),请直接使用get(String key, Class<T> clazz)取值
  119. *
  120. * @param key
  121. * @return
  122. */
  123. public static Object getObj(String key) {
  124. return redisTemplate1.boundValueOps(key).get();
  125. }
  126. /**
  127. * 获取缓存<br>
  128. * 注:java 8种基本类型的数据请直接使用get(String key, Class<T> 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. * 获取缓存<br>
  144. * 注:该方法暂不支持Character数据类型
  145. *
  146. * @param key
  147. * key
  148. * @param clazz
  149. * 类型
  150. * @return
  151. */
  152. @SuppressWarnings("unchecked")
  153. public <T> T get(String key, Class<T> clazz) {
  154. return (T) redisTemplate1.boundValueOps(key).get();
  155. }
  156. /**
  157. * 获取缓存json对象<br>
  158. *
  159. * @param key
  160. * key
  161. * @param clazz
  162. * 类型
  163. * @return
  164. * @throws Exception
  165. @SuppressWarnings("unchecked")
  166. public <T> T getJson(String key, Class<T> 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 <T> void setMap(String key, Map<String, T> 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 <T> void setMap(String key, T obj, Long time) {
  317. Map<String, String> map = (Map<String, String>)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 <T> void addMap(String key, Map<String, T> 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 <T> 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 <T> Map<String, T> mget(String key, Class<T> clazz) {
  363. BoundHashOperations<String, String, T> 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> T getMapField(String key, String field, Class<T> 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> T getMap(String key, Class<T> clazz) {
  385. BoundHashOperations<String, String, String> boundHashOperations = redisTemplate.boundHashOps(key);
  386. Map<String, String> 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<String, String, ?> 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<String> 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<String, Object> getRedisTemplate() {
  493. redisTemplate1 = redisTemplate;
  494. System.out.println("获取缓存: getStringRedisTemplate ... " + stringRedisTemplate.toString());
  495. return redisTemplate1;
  496. }
  497. public void setRedisTemplate(RedisTemplate<String, Object> 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<AlarmData> list = JSONArray.parseArray(alarmDataStr , AlarmData.class);
  8. //List<AlarmData> 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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/152198
推荐阅读
相关标签
  

闽ICP备14008679号