SpringBoot集成Redis——RedisTemplate方式

深碍√TFBOYSˉ_ 2022-03-16 05:28 1173阅读 0赞

本篇基于Springboot2.0 + Redis实现数据缓存以及分库存储,首先我们要知道,Springboot整合Redis有两种方式,分别是Jedis和RedisTemplate,这两者有何区别?

Jedis是Redis官方推荐的面向Java的操作Redis的客户端,而RedisTemplate是SpringDataRedis中对JedisApi的高度封装。其实在Springboot的官网上我们也能看到,官方现在推荐的是SpringDataRedis形式,相对于Jedis来说可以方便地更换Redis的Java客户端,其比Jedis多了自动管理连接池的特性,方便与其他Spring框架进行搭配使用如:SpringCache。

一、Redis基本配置及工具类

首先我们看下整个项目的目录结构,共分为三部分,pom包在文末给出

70

1.创建redis.properties配置文件

  1. #Matser的ip地址
  2. redis.hostName=localhost
  3. #端口号
  4. redis.port=6379
  5. #如果有密码
  6. redis.password=123456
  7. #客户端超时时间单位是毫秒 默认是2000
  8. redis.timeout=10000
  9. #最大空闲数
  10. redis.maxIdle=300
  11. #连接池的最大数据库连接数。设为0表示无限制,如果是jedis 2.4以后用redis.maxTotal
  12. #redis.maxActive=600
  13. #控制一个pool可分配多少个jedis实例,用来替换上面的redis.maxActive,如果是jedis 2.4以后用该属性
  14. redis.maxTotal=1000
  15. #最大建立连接等待时间。如果超过此时间将接到异常。设为-1表示无限制。
  16. redis.maxWaitMillis=1000
  17. #连接的最小空闲时间 默认1800000毫秒(30分钟)
  18. redis.minEvictableIdleTimeMillis=300000
  19. #每次释放连接的最大数目,默认3
  20. redis.numTestsPerEvictionRun=1024
  21. #逐出扫描的时间间隔(毫秒) 如果为负数,则不运行逐出线程, 默认-1
  22. redis.timeBetweenEvictionRunsMillis=30000
  23. #是否在从池中取出连接前进行检验,如果检验失败,则从池中去除连接并尝试取出另一个
  24. redis.testOnBorrow=true
  25. #在空闲时检查有效性, 默认false
  26. redis.testWhileIdle=true

这些配置并不一定都需要,按照情况添加,全都添加也无大碍,其中我们必须要指定Redis的地址,端口及密码

2.添加配置类RedisConfig.java

  1. package com.springboot.demo.base.config;
  2. import com.springboot.demo.base.utils.FastJson2JsonRedisSerializer;
  3. import com.springboot.demo.base.utils.RedisUtil;
  4. import lombok.extern.slf4j.Slf4j;
  5. import org.springframework.beans.factory.annotation.Value;
  6. import org.springframework.context.annotation.Bean;
  7. import org.springframework.context.annotation.Configuration;
  8. import org.springframework.context.annotation.PropertySource;
  9. import org.springframework.data.redis.connection.RedisConnectionFactory;
  10. import org.springframework.data.redis.connection.RedisPassword;
  11. import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
  12. import org.springframework.data.redis.connection.jedis.JedisClientConfiguration;
  13. import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
  14. import com.springboot.demo.base.utils.RedisTemplate;
  15. import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
  16. import org.springframework.data.redis.serializer.RedisSerializer;
  17. import org.springframework.data.redis.serializer.StringRedisSerializer;
  18. import java.time.Duration;
  19. /**
  20. * @ClassName: RedisConfig
  21. * @Auther: zhangyingqi
  22. * @Date: 2018/8/28 11:07
  23. * @Description:
  24. */
  25. @Configuration
  26. @PropertySource("classpath:redis.properties")
  27. @Slf4j
  28. public class RedisConfig {
  29. @Value("${redis.hostName}")
  30. private String hostName;
  31. @Value("${redis.password}")
  32. private String password;
  33. @Value("${redis.port}")
  34. private Integer port;
  35. @Value("${redis.maxIdle}")
  36. private Integer maxIdle;
  37. @Value("${redis.timeout}")
  38. private Integer timeout;
  39. @Value("${redis.maxTotal}")
  40. private Integer maxTotal;
  41. @Value("${redis.maxWaitMillis}")
  42. private Integer maxWaitMillis;
  43. @Value("${redis.minEvictableIdleTimeMillis}")
  44. private Integer minEvictableIdleTimeMillis;
  45. @Value("${redis.numTestsPerEvictionRun}")
  46. private Integer numTestsPerEvictionRun;
  47. @Value("${redis.timeBetweenEvictionRunsMillis}")
  48. private long timeBetweenEvictionRunsMillis;
  49. @Value("${redis.testOnBorrow}")
  50. private boolean testOnBorrow;
  51. @Value("${redis.testWhileIdle}")
  52. private boolean testWhileIdle;
  53. /**
  54. * @auther: zhangyingqi
  55. * @date: 17:52 2018/8/28
  56. * @param: []
  57. * @return: org.springframework.data.redis.connection.jedis.JedisConnectionFactory
  58. * @Description: Jedis配置
  59. */
  60. @Bean
  61. public JedisConnectionFactory JedisConnectionFactory(){
  62. RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration ();
  63. redisStandaloneConfiguration.setHostName(hostName);
  64. redisStandaloneConfiguration.setPort(port);
  65. //由于我们使用了动态配置库,所以此处省略
  66. //redisStandaloneConfiguration.setDatabase(database);
  67. redisStandaloneConfiguration.setPassword(RedisPassword.of(password));
  68. JedisClientConfiguration.JedisClientConfigurationBuilder jedisClientConfiguration = JedisClientConfiguration.builder();
  69. jedisClientConfiguration.connectTimeout(Duration.ofMillis(timeout));
  70. JedisConnectionFactory factory = new JedisConnectionFactory(redisStandaloneConfiguration,
  71. jedisClientConfiguration.build());
  72. return factory;
  73. }
  74. /**
  75. * @auther: zhangyingqi
  76. * @date: 17:52 2018/8/28
  77. * @param: [redisConnectionFactory]
  78. * @return: com.springboot.demo.base.utils.RedisTemplate
  79. * @Description: 实例化 RedisTemplate 对象
  80. */
  81. @Bean
  82. public RedisTemplate functionDomainRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
  83. log.info("RedisTemplate实例化成功!");
  84. RedisTemplate redisTemplate = new RedisTemplate();
  85. initDomainRedisTemplate(redisTemplate, redisConnectionFactory);
  86. return redisTemplate;
  87. }
  88. /**
  89. * @auther: zhangyingqi
  90. * @date: 17:52 2018/8/28
  91. * @param: []
  92. * @return: org.springframework.data.redis.serializer.RedisSerializer
  93. * @Description: 引入自定义序列化
  94. */
  95. @Bean
  96. public RedisSerializer fastJson2JsonRedisSerializer() {
  97. return new FastJson2JsonRedisSerializer<Object>(Object.class);
  98. }
  99. /**
  100. * @auther: zhangyingqi
  101. * @date: 17:51 2018/8/28
  102. * @param: [redisTemplate, factory]
  103. * @return: void
  104. * @Description: 设置数据存入 redis 的序列化方式,并开启事务
  105. */
  106. private void initDomainRedisTemplate(RedisTemplate redisTemplate, RedisConnectionFactory factory) {
  107. //如果不配置Serializer,那么存储的时候缺省使用String,如果用User类型存储,那么会提示错误User can't cast to String!
  108. redisTemplate.setKeySerializer(new StringRedisSerializer());
  109. redisTemplate.setHashKeySerializer(new StringRedisSerializer());
  110. redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
  111. redisTemplate.setValueSerializer(fastJson2JsonRedisSerializer());
  112. // 开启事务
  113. redisTemplate.setEnableTransactionSupport(true);
  114. redisTemplate.setConnectionFactory(factory);
  115. }
  116. /**
  117. * @auther: zhangyingqi
  118. * @date: 17:51 2018/8/28
  119. * @param: [redisTemplate]
  120. * @return: com.springboot.demo.base.utils.RedisUtil
  121. * @Description: 注入封装RedisTemplate
  122. */
  123. @Bean(name = "redisUtil")
  124. public RedisUtil redisUtil(RedisTemplate redisTemplate) {
  125. log.info("RedisUtil注入成功!");
  126. RedisUtil redisUtil = new RedisUtil();
  127. redisUtil.setRedisTemplate(redisTemplate);
  128. return redisUtil;
  129. }
  130. }

3.然后补充其他依赖,为了实现分库存储,我们必须重写自带的RedisTemplate。

该类继承了springdataredis的RedisTemplate类,我们加入indexdb为Redis库的编号,重写了里面的RedisConnection方法,加入是否有库值传递进来的逻辑判断。

  1. package com.springboot.demo.base.utils;
  2. import org.springframework.data.redis.connection.RedisConnection;
  3. import org.springframework.data.redis.connection.jedis.JedisConnection;
  4. /**
  5. * @ClassName: RedisTemplate
  6. * @Auther: zhangyingqi
  7. * @Date: 2018/8/28 16:15
  8. * @Description: 重写RedisTemplate,加入选库
  9. */
  10. public class RedisTemplate extends org.springframework.data.redis.core.RedisTemplate {
  11. public static ThreadLocal<Integer> indexdb = new ThreadLocal<Integer>(){
  12. @Override protected Integer initialValue() { return 0; }
  13. };
  14. @Override
  15. protected RedisConnection preProcessConnection(RedisConnection connection, boolean existingConnection) {
  16. try {
  17. Integer dbIndex = indexdb.get();
  18. //如果设置了dbIndex
  19. if (dbIndex != null) {
  20. if (connection instanceof JedisConnection) {
  21. if (((JedisConnection) connection).getNativeConnection().getDB().intValue() != dbIndex) {
  22. connection.select(dbIndex);
  23. }
  24. } else {
  25. connection.select(dbIndex);
  26. }
  27. } else {
  28. connection.select(0);
  29. }
  30. } finally {
  31. indexdb.remove();
  32. }
  33. return super.preProcessConnection(connection, existingConnection);
  34. }
  35. }

4.接下来还需要一个序列化操作类,帮助我们完成redis值的序列化。

添加FastJson2JsonRedisSerializer.java,实现RedisSerializer接口,实现其中的序列化和反序列化方法。

  1. package com.springboot.demo.base.utils;
  2. import com.alibaba.fastjson.JSON;
  3. import com.alibaba.fastjson.serializer.SerializerFeature;
  4. import org.springframework.data.redis.serializer.RedisSerializer;
  5. import org.springframework.data.redis.serializer.SerializationException;
  6. import java.nio.charset.Charset;
  7. /**
  8. * @ClassName: FastJson2JsonRedisSerializer
  9. * @Auther: zhangyingqi
  10. * @Date: 2018/8/28 16:11
  11. * @Description: 自定义序列化
  12. */
  13. public class FastJson2JsonRedisSerializer<T> implements RedisSerializer<T> {
  14. public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
  15. private Class<T> clazz;
  16. public FastJson2JsonRedisSerializer(Class<T> clazz) {
  17. super(); this.clazz = clazz;
  18. }
  19. @Override
  20. public byte[] serialize(T t) throws SerializationException {
  21. if (t == null) {
  22. return new byte[0];
  23. }
  24. return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET);
  25. }
  26. @Override
  27. public T deserialize(byte[] bytes) throws SerializationException {
  28. if (bytes == null || bytes.length <= 0) {
  29. return null;
  30. }
  31. String str = new String(bytes, DEFAULT_CHARSET);
  32. return (T) JSON.parseObject(str, clazz);
  33. }
  34. }

5.添加RedisUtil.java,这就是最后实际操作中调用的redis操作工具类。

其中内容不具备分库操作的,所以我对其进行了改造,使得最终我们可以根据需要向不同的库中存储数据。

  1. package com.springboot.demo.base.utils;
  2. import java.util.List;
  3. import java.util.Map;
  4. import java.util.Set;
  5. import java.util.concurrent.TimeUnit;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.context.annotation.Lazy;
  8. import com.springboot.demo.base.utils.RedisTemplate;
  9. import org.springframework.stereotype.Component;
  10. import org.springframework.util.CollectionUtils;
  11. @Lazy
  12. @Component
  13. public class RedisUtil{
  14. @Autowired
  15. private RedisTemplate redisTemplate;
  16. public void setRedisTemplate(RedisTemplate redisTemplate) {
  17. this.redisTemplate = redisTemplate;
  18. }
  19. //=============================common============================
  20. /**
  21. * 指定缓存失效时间
  22. * @param key 键
  23. * @param time 时间(秒)
  24. * @return
  25. */
  26. public boolean expire(String key,long time){
  27. try {
  28. if(time>0){
  29. redisTemplate.expire(key, time, TimeUnit.SECONDS);
  30. }
  31. return true;
  32. } catch (Exception e) {
  33. e.printStackTrace();
  34. return false;
  35. }
  36. }
  37. /**
  38. * 根据key 获取过期时间
  39. * @param key 键 不能为null
  40. * @return 时间(秒) 返回0代表为永久有效
  41. */
  42. public long getExpire(String key){
  43. return redisTemplate.getExpire(key,TimeUnit.SECONDS);
  44. }
  45. /**
  46. * 判断key是否存在
  47. * @param key 键
  48. * @return true 存在 false不存在
  49. */
  50. public boolean hasKey(String key){
  51. try {
  52. return redisTemplate.hasKey(key);
  53. } catch (Exception e) {
  54. e.printStackTrace();
  55. return false;
  56. }
  57. }
  58. /**
  59. * 删除缓存
  60. * @param key 可以传一个值 或多个
  61. */
  62. @SuppressWarnings("unchecked")
  63. public void del(String ... key){
  64. if(key!=null&&key.length>0){
  65. if(key.length==1){
  66. redisTemplate.delete(key[0]);
  67. }else{
  68. redisTemplate.delete(CollectionUtils.arrayToList(key));
  69. }
  70. }
  71. }
  72. //============================String=============================
  73. /**
  74. * 普通缓存获取
  75. * @param key 键
  76. * @return 值
  77. */
  78. public Object get(String key, int indexdb){
  79. redisTemplate.indexdb.set(indexdb);
  80. return key==null?null:redisTemplate.opsForValue().get(key);
  81. }
  82. /**
  83. * 普通缓存放入
  84. * @param key 键
  85. * @param value 值
  86. * @return true成功 false失败
  87. */
  88. public boolean set(String key,Object value,int indexdb) {
  89. try {
  90. redisTemplate.indexdb.set(indexdb);
  91. redisTemplate.opsForValue().set(key, value);
  92. return true;
  93. } catch (Exception e) {
  94. e.printStackTrace();
  95. return false;
  96. }
  97. }
  98. /**
  99. * 普通缓存放入并设置时间
  100. * @param key 键
  101. * @param value 值
  102. * @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期
  103. * @return true成功 false 失败
  104. */
  105. public boolean set(String key,Object value,long time){
  106. try {
  107. if(time>0){
  108. redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
  109. }else{
  110. redisTemplate.opsForValue().set(key, value);
  111. }
  112. return true;
  113. } catch (Exception e) {
  114. e.printStackTrace();
  115. return false;
  116. }
  117. }
  118. /**
  119. * 递增
  120. * @param key 键
  121. * @param by 要增加几(大于0)
  122. * @return
  123. */
  124. public long incr(String key, long delta){
  125. if(delta<0){
  126. throw new RuntimeException("递增因子必须大于0");
  127. }
  128. return redisTemplate.opsForValue().increment(key, delta);
  129. }
  130. /**
  131. * 递减
  132. * @param key 键
  133. * @param by 要减少几(小于0)
  134. * @return
  135. */
  136. public long decr(String key, long delta){
  137. if(delta<0){
  138. throw new RuntimeException("递减因子必须大于0");
  139. }
  140. return redisTemplate.opsForValue().increment(key, -delta);
  141. }
  142. //================================Map=================================
  143. /**
  144. * HashGet
  145. * @param key 键 不能为null
  146. * @param item 项 不能为null
  147. * @return 值
  148. */
  149. public Object hget(String key,String item){
  150. return redisTemplate.opsForHash().get(key, item);
  151. }
  152. /**
  153. * 获取hashKey对应的所有键值
  154. * @param key 键
  155. * @return 对应的多个键值
  156. */
  157. public Map<Object,Object> hmget(String key){
  158. return redisTemplate.opsForHash().entries(key);
  159. }
  160. /**
  161. * HashSet
  162. * @param key 键
  163. * @param map 对应多个键值
  164. * @return true 成功 false 失败
  165. */
  166. public boolean hmset(String key, Map<String,Object> map){
  167. try {
  168. redisTemplate.opsForHash().putAll(key, map);
  169. return true;
  170. } catch (Exception e) {
  171. e.printStackTrace();
  172. return false;
  173. }
  174. }
  175. /**
  176. * HashSet 并设置时间
  177. * @param key 键
  178. * @param map 对应多个键值
  179. * @param time 时间(秒)
  180. * @return true成功 false失败
  181. */
  182. public boolean hmset(String key, Map<String,Object> map, long time){
  183. try {
  184. redisTemplate.opsForHash().putAll(key, map);
  185. if(time>0){
  186. expire(key, time);
  187. }
  188. return true;
  189. } catch (Exception e) {
  190. e.printStackTrace();
  191. return false;
  192. }
  193. }
  194. /**
  195. * 向一张hash表中放入数据,如果不存在将创建
  196. * @param key 键
  197. * @param item 项
  198. * @param value 值
  199. * @return true 成功 false失败
  200. */
  201. public boolean hset(String key,String item,Object value) {
  202. try {
  203. redisTemplate.opsForHash().put(key, item, value);
  204. return true;
  205. } catch (Exception e) {
  206. e.printStackTrace();
  207. return false;
  208. }
  209. }
  210. /**
  211. * 向一张hash表中放入数据,如果不存在将创建
  212. * @param key 键
  213. * @param item 项
  214. * @param value 值
  215. * @param time 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
  216. * @return true 成功 false失败
  217. */
  218. public boolean hset(String key,String item,Object value,long time) {
  219. try {
  220. redisTemplate.opsForHash().put(key, item, value);
  221. if(time>0){
  222. expire(key, time);
  223. }
  224. return true;
  225. } catch (Exception e) {
  226. e.printStackTrace();
  227. return false;
  228. }
  229. }
  230. /**
  231. * 删除hash表中的值
  232. * @param key 键 不能为null
  233. * @param item 项 可以使多个 不能为null
  234. */
  235. public void hdel(String key, Object... item){
  236. redisTemplate.opsForHash().delete(key,item);
  237. }
  238. /**
  239. * 判断hash表中是否有该项的值
  240. * @param key 键 不能为null
  241. * @param item 项 不能为null
  242. * @return true 存在 false不存在
  243. */
  244. public boolean hHasKey(String key, String item){
  245. return redisTemplate.opsForHash().hasKey(key, item);
  246. }
  247. /**
  248. * hash递增 如果不存在,就会创建一个 并把新增后的值返回
  249. * @param key 键
  250. * @param item 项
  251. * @param by 要增加几(大于0)
  252. * @return
  253. */
  254. public double hincr(String key, String item,double by){
  255. return redisTemplate.opsForHash().increment(key, item, by);
  256. }
  257. /**
  258. * hash递减
  259. * @param key 键
  260. * @param item 项
  261. * @param by 要减少记(小于0)
  262. * @return
  263. */
  264. public double hdecr(String key, String item,double by){
  265. return redisTemplate.opsForHash().increment(key, item,-by);
  266. }
  267. //============================set=============================
  268. /**
  269. * 根据key获取Set中的所有值
  270. * @param key 键
  271. * @return
  272. */
  273. public Set<Object> sGet(String key){
  274. try {
  275. return redisTemplate.opsForSet().members(key);
  276. } catch (Exception e) {
  277. e.printStackTrace();
  278. return null;
  279. }
  280. }
  281. /**
  282. * 根据value从一个set中查询,是否存在
  283. * @param key 键
  284. * @param value 值
  285. * @return true 存在 false不存在
  286. */
  287. public boolean sHasKey(String key,Object value){
  288. try {
  289. return redisTemplate.opsForSet().isMember(key, value);
  290. } catch (Exception e) {
  291. e.printStackTrace();
  292. return false;
  293. }
  294. }
  295. /**
  296. * 将数据放入set缓存
  297. * @param key 键
  298. * @param values 值 可以是多个
  299. * @return 成功个数
  300. */
  301. public long sSet(String key, Object...values) {
  302. try {
  303. return redisTemplate.opsForSet().add(key, values);
  304. } catch (Exception e) {
  305. e.printStackTrace();
  306. return 0;
  307. }
  308. }
  309. /**
  310. * 将set数据放入缓存
  311. * @param key 键
  312. * @param time 时间(秒)
  313. * @param values 值 可以是多个
  314. * @return 成功个数
  315. */
  316. public long sSetAndTime(String key,long time,Object...values) {
  317. try {
  318. Long count = redisTemplate.opsForSet().add(key, values);
  319. if(time>0) expire(key, time);
  320. return count;
  321. } catch (Exception e) {
  322. e.printStackTrace();
  323. return 0;
  324. }
  325. }
  326. /**
  327. * 获取set缓存的长度
  328. * @param key 键
  329. * @return
  330. */
  331. public long sGetSetSize(String key){
  332. try {
  333. return redisTemplate.opsForSet().size(key);
  334. } catch (Exception e) {
  335. e.printStackTrace();
  336. return 0;
  337. }
  338. }
  339. /**
  340. * 移除值为value的
  341. * @param key 键
  342. * @param values 值 可以是多个
  343. * @return 移除的个数
  344. */
  345. public long setRemove(String key, Object ...values) {
  346. try {
  347. Long count = redisTemplate.opsForSet().remove(key, values);
  348. return count;
  349. } catch (Exception e) {
  350. e.printStackTrace();
  351. return 0;
  352. }
  353. }
  354. //===============================list=================================
  355. /**
  356. * 获取list缓存的内容
  357. * @param key 键
  358. * @param start 开始
  359. * @param end 结束 0 到 -1代表所有值
  360. * @return
  361. */
  362. public List<Object> lGet(String key,long start, long end){
  363. try {
  364. return redisTemplate.opsForList().range(key, start, end);
  365. } catch (Exception e) {
  366. e.printStackTrace();
  367. return null;
  368. }
  369. }
  370. /**
  371. * 获取list缓存的长度
  372. * @param key 键
  373. * @return
  374. */
  375. public long lGetListSize(String key){
  376. try {
  377. return redisTemplate.opsForList().size(key);
  378. } catch (Exception e) {
  379. e.printStackTrace();
  380. return 0;
  381. }
  382. }
  383. /**
  384. * 通过索引 获取list中的值
  385. * @param key 键
  386. * @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
  387. * @return
  388. */
  389. public Object lGetIndex(String key,long index){
  390. try {
  391. return redisTemplate.opsForList().index(key, index);
  392. } catch (Exception e) {
  393. e.printStackTrace();
  394. return null;
  395. }
  396. }
  397. /**
  398. * 将list放入缓存
  399. * @param key 键
  400. * @param value 值
  401. * @param time 时间(秒)
  402. * @return
  403. */
  404. public boolean lSet(String key, Object value) {
  405. try {
  406. redisTemplate.opsForList().rightPush(key, value);
  407. return true;
  408. } catch (Exception e) {
  409. e.printStackTrace();
  410. return false;
  411. }
  412. }
  413. /**
  414. * 将list放入缓存
  415. * @param key 键
  416. * @param value 值
  417. * @param time 时间(秒)
  418. * @return
  419. */
  420. public boolean lSet(String key, Object value, long time) {
  421. try {
  422. redisTemplate.opsForList().rightPush(key, value);
  423. if (time > 0) expire(key, time);
  424. return true;
  425. } catch (Exception e) {
  426. e.printStackTrace();
  427. return false;
  428. }
  429. }
  430. /**
  431. * 将list放入缓存
  432. * @param key 键
  433. * @param value 值
  434. * @param time 时间(秒)
  435. * @return
  436. */
  437. public boolean lSet(String key, List<Object> value) {
  438. try {
  439. redisTemplate.opsForList().rightPushAll(key, value);
  440. return true;
  441. } catch (Exception e) {
  442. e.printStackTrace();
  443. return false;
  444. }
  445. }
  446. /**
  447. * 将list放入缓存
  448. * @param key 键
  449. * @param value 值
  450. * @param time 时间(秒)
  451. * @return
  452. */
  453. public boolean lSet(String key, List<Object> value, long time) {
  454. try {
  455. redisTemplate.opsForList().rightPushAll(key, value);
  456. if (time > 0) expire(key, time);
  457. return true;
  458. } catch (Exception e) {
  459. e.printStackTrace();
  460. return false;
  461. }
  462. }
  463. /**
  464. * 根据索引修改list中的某条数据
  465. * @param key 键
  466. * @param index 索引
  467. * @param value 值
  468. * @return
  469. */
  470. public boolean lUpdateIndex(String key, long index,Object value) {
  471. try {
  472. redisTemplate.opsForList().set(key, index, value);
  473. return true;
  474. } catch (Exception e) {
  475. e.printStackTrace();
  476. return false;
  477. }
  478. }
  479. /**
  480. * 移除N个值为value
  481. * @param key 键
  482. * @param count 移除多少个
  483. * @param value 值
  484. * @return 移除的个数
  485. */
  486. public long lRemove(String key,long count,Object value) {
  487. try {
  488. Long remove = redisTemplate.opsForList().remove(key, count, value);
  489. return remove;
  490. } catch (Exception e) {
  491. e.printStackTrace();
  492. return 0;
  493. }
  494. }
  495. public static void main(String[] args) {
  496. /*JedisPool jedisPool = new JedisPool(null,"localhost",6379,100,"123456");
  497. Jedis jedis = jedisPool.getResource();
  498. //r.get("", RedisConstants.datebase4);
  499. jedis.select(RedisConstants.datebase4);
  500. Set<String> str = jedis.keys("*");
  501. for (String string : str) {
  502. System.out.println(string);
  503. }*/
  504. }
  505. }

具体的改造过程示例:

  1. public boolean set(String key,Object value,int indexdb) {
  2. try {
  3. redisTemplate.indexdb.set(indexdb);
  4. redisTemplate.opsForValue().set(key, value);
  5. return true;
  6. } catch (Exception e) {
  7. e.printStackTrace();
  8. return false;
  9. }
  10. }

这是一个最基本的set方法,加入int型的indexdb参数,用来接收库编号,通过redisTemplate.indexdb.set(indexdb);完成选库操作,由于我们在内部使用finally清除了选库,所以不必担心下次操作库的缓存问题。

依次在你需要改造的地方做对应的修改即可。

二、实际操作示例

我这里直接拿现成的controller做演示,不再独立编写测试类

新建RedisTestController.java

  1. package com.springboot.demo.controller;
  2. import com.springboot.demo.base.controller.BaseController;
  3. import com.springboot.demo.base.utils.RedisConstants;
  4. import com.springboot.demo.base.utils.RedisUtil;
  5. import com.springboot.demo.base.utils.StateParameter;
  6. import com.springboot.demo.entity.User;
  7. import org.springframework.beans.factory.annotation.Autowired;
  8. import org.springframework.stereotype.Controller;
  9. import org.springframework.ui.ModelMap;
  10. import org.springframework.web.bind.annotation.RequestMapping;
  11. import org.springframework.web.bind.annotation.ResponseBody;
  12. /**
  13. * @ClassName: RedisTestController
  14. * @Auther: zhangyingqi
  15. * @Date: 2018/8/28 17:24
  16. * @Description:
  17. */
  18. @Controller
  19. @RequestMapping("/redis")
  20. public class RedisTestController extends BaseController{
  21. @Autowired
  22. RedisUtil redisUtil;
  23. /**
  24. * @auther: zhangyingqi
  25. * @date: 17:26 2018/8/28
  26. * @param: []
  27. * @return: org.springframework.ui.ModelMap
  28. * @Description: 测试redis存储&读取
  29. */
  30. @RequestMapping(value="/test")
  31. @ResponseBody
  32. public ModelMap test(){
  33. try {
  34. redisUtil.set("redisTemplate","这是一条测试数据", RedisConstants.datebase2);
  35. String value = redisUtil.get("redisTemplate",RedisConstants.datebase2).toString();
  36. logger.info("redisValue="+value);
  37. logger.info("读取redis成功");
  38. return getModelMap(StateParameter.SUCCESS, value, "操作成功");
  39. } catch (Exception e) {
  40. e.printStackTrace();
  41. return getModelMap(StateParameter.FAULT, null, "操作失败");
  42. }
  43. }
  44. @RequestMapping(value="/setUser")
  45. @ResponseBody
  46. public ModelMap setUser(){
  47. try {
  48. User user = new User();
  49. user.setName("隔壁老王");
  50. user.setAge(28);
  51. user.setId(getUuid());
  52. redisUtil.set("user",user, RedisConstants.datebase1);
  53. User res = (User)redisUtil.get("user",RedisConstants.datebase1);
  54. logger.info("res="+res.toString());
  55. logger.info("读取redis成功");
  56. return getModelMap(StateParameter.SUCCESS, res, "操作成功");
  57. } catch (Exception e) {
  58. e.printStackTrace();
  59. return getModelMap(StateParameter.FAULT, null, "操作失败");
  60. }
  61. }
  62. }

这里使用@Autowired注入RedisUtil

  1. @Autowired
  2. RedisUtil redisUtil;

使用以下语句将字符串存入redis的库2中

  1. redisUtil.set("redisTemplate","这是一条测试数据", RedisConstants.datebase2);

启动项目执行操作,后台可以看到实例化成功

70 1

输入测试地址:http://localhost:8080/redis/test,返回成功,打开redis客户端工具,可以看到在db2中存入了该数据

70 2

最后给出pom包

  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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <groupId>com.springboot</groupId>
  6. <artifactId>springbootRedis</artifactId>
  7. <version>0.0.1-SNAPSHOT</version>
  8. <packaging>war</packaging>
  9. <name>springbootRedis</name>
  10. <description>Demo project for Spring Boot</description>
  11. <parent>
  12. <groupId>org.springframework.boot</groupId>
  13. <artifactId>spring-boot-starter-parent</artifactId>
  14. <version>2.0.4.RELEASE</version>
  15. <relativePath/> <!-- lookup parent from repository -->
  16. </parent>
  17. <properties>
  18. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  19. <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  20. <java.version>1.8</java.version>
  21. </properties>
  22. <dependencies>
  23. <dependency>
  24. <groupId>org.springframework.boot</groupId>
  25. <artifactId>spring-boot-starter-tomcat</artifactId>
  26. <!--<scope>provided</scope>-->
  27. </dependency>
  28. <dependency>
  29. <groupId>org.springframework.boot</groupId>
  30. <artifactId>spring-boot-starter-data-jpa</artifactId>
  31. <exclusions>
  32. <exclusion>
  33. <groupId>org.hibernate</groupId>
  34. <artifactId>hibernate-entitymanager</artifactId>
  35. </exclusion>
  36. <exclusion>
  37. <groupId>org.hibernate</groupId>
  38. <artifactId>hibernate-core</artifactId>
  39. </exclusion>
  40. </exclusions>
  41. </dependency>
  42. <dependency>
  43. <groupId>org.hibernate</groupId>
  44. <artifactId>hibernate-core</artifactId>
  45. <version>5.2.10.Final</version>
  46. </dependency>
  47. <dependency>
  48. <groupId>org.springframework.boot</groupId>
  49. <artifactId>spring-boot-starter-data-redis</artifactId>
  50. </dependency>
  51. <dependency>
  52. <groupId>org.springframework.boot</groupId>
  53. <artifactId>spring-boot-starter-mail</artifactId>
  54. </dependency>
  55. <dependency>
  56. <groupId>org.springframework.boot</groupId>
  57. <artifactId>spring-boot-starter-thymeleaf</artifactId>
  58. </dependency>
  59. <dependency>
  60. <groupId>org.springframework.boot</groupId>
  61. <artifactId>spring-boot-starter-web</artifactId>
  62. </dependency>
  63. <dependency>
  64. <groupId>mysql</groupId>
  65. <artifactId>mysql-connector-java</artifactId>
  66. <scope>runtime</scope>
  67. </dependency>
  68. <dependency>
  69. <groupId>org.projectlombok</groupId>
  70. <artifactId>lombok</artifactId>
  71. <optional>true</optional>
  72. </dependency>
  73. <dependency>
  74. <groupId>org.springframework.boot</groupId>
  75. <artifactId>spring-boot-starter-test</artifactId>
  76. <scope>test</scope>
  77. </dependency>
  78. <dependency>
  79. <groupId>redis.clients</groupId>
  80. <artifactId>jedis</artifactId>
  81. <version>2.9.0</version>
  82. </dependency>
  83. <dependency>
  84. <groupId>commons-io</groupId>
  85. <artifactId>commons-io</artifactId>
  86. <version>2.6</version>
  87. </dependency>
  88. <dependency>
  89. <groupId>com.alibaba</groupId>
  90. <artifactId>fastjson</artifactId>
  91. <version>1.2.38</version>
  92. </dependency>
  93. </dependencies>
  94. <build>
  95. <plugins>
  96. <plugin>
  97. <groupId>org.springframework.boot</groupId>
  98. <artifactId>spring-boot-maven-plugin</artifactId>
  99. </plugin>
  100. </plugins>
  101. </build>
  102. </project>

原文:https://blog.csdn.net/zhulier1124/article/details/82154937

GitHub地址:https://github.com/jwwam/springbootRedis.git

发表评论

表情:
评论列表 (有 0 条评论,1173人围观)

还没有评论,来说两句吧...

相关阅读