• 从0到1学SpringCloud——10 springboot集成redis缓存


    目录

    一、前言

    二、pom依赖

    三、redis配置

    四、代码测试

    五、序列化配置

    六、工具类改造

    七、注意事项


    一、前言

    本篇主要讲解springboot集成redis的使用方式,工具类的封装及使用。

    二、pom依赖

    1. <dependency>
    2. <groupId>org.springframework.bootgroupId>
    3. <artifactId>spring-boot-starter-data-redisartifactId>
    4. dependency>
    5. <dependency>
    6. <groupId>org.apache.commonsgroupId>
    7. <artifactId>commons-pool2artifactId>
    8. dependency>

    如果没有引用commons-pool2依赖

    项目启动控制台报错:org.apache.commons.pool2.impl.GenericObjectPoolConfig

    1. Caused by: java.lang.ClassNotFoundException: org.apache.commons.pool2.impl.GenericObjectPoolConfig
    2. at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:641) ~[na:na]
    3. at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188) ~[na:na]
    4. at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521) ~[na:na]
    5. ... 58 common frames omitted

    三、redis配置

    1. # Redis服务器地址
    2. spring.redis.host=127.0.0.1
    3. # Redis服务器连接端口
    4. spring.redis.port=6379
    5. # Redis服务器连接密码(默认为空)
    6. #spring.redis.password=redis
    7. # Redis数据库索引(默认为0)
    8. spring.redis.database=0
    9. # 连接超时时间(毫秒)
    10. spring.redis.timeout=10000
    11. # Redis默认情况下有16个分片,这里配置具体使用的分片,默认是0
    12. spring.redis.database=0
    13. # 连接池最大连接数(使用负值表示没有限制) 默认 8
    14. spring.redis.lettuce.pool.max-active=8
    15. # 连接池最大阻塞等待时间(使用负值表示没有限制) 默认 -1
    16. spring.redis.lettuce.pool.max-wait=-1
    17. # 连接池中的最大空闲连接 默认 8
    18. spring.redis.lettuce.pool.max-idle=8
    19. # 连接池中的最小空闲连接 默认 0
    20. spring.redis.lettuce.pool.min-idle=0

    配置项中指定了数据库索引

    # Redis数据库索引(默认为0)
    spring.redis.database=0

    redis有十六个库,相当于一个数据库的中的十六张表,可以用来数据分类,或者不同测试环境数据区分。

    四、代码测试

    1. import org.springframework.data.redis.core.RedisTemplate;
    2. import org.springframework.web.bind.annotation.RequestMapping;
    3. import org.springframework.web.bind.annotation.RestController;
    4. import javax.annotation.Resource;
    5. /**
    6. * @ClassName: DataController
    7. * @Description redis链接测试
    8. * @author 月夜烛峰
    9. * @date 2022/9/5 19:40
    10. */
    11. @RestController
    12. @RequestMapping("data")
    13. public class DataController {
    14. @Resource
    15. RedisTemplate redisTemplate;
    16. @RequestMapping("redis")
    17. public Object showRedis(){
    18. redisTemplate.opsForValue().set("zhufeng-test", "测试");
    19. return redisTemplate.opsForValue().get("zhufeng-test");
    20. }
    21. }

    @Resource
    RedisTemplate redisTemplate;

    完成配置后,在项目启动时,会完成redis的自动装配,springboot可以获取到redisTemplate。

    springboot自动装配的原理可参考:

    深入理解springboot的自动配置「源码分析/图文详解」

    启动项目,访问http://127.0.0.1:8080/data/redis

    通过redis客户端进入查看:

    代码中添加的key是 zhufeng-test,好像有些出入。

    RedisTemplate设置redis的key时出现\xac\xed\x00\x05t\x00\x0f前缀 
    出现这种乱码前缀的原因是没有进行序列化,因此导致在传输过程出现乱码问题。
    RedisTemplate类中默认是没有设置序列化的。

    五、序列化配置

    1. import com.fasterxml.jackson.annotation.JsonAutoDetect;
    2. import com.fasterxml.jackson.annotation.PropertyAccessor;
    3. import com.fasterxml.jackson.databind.ObjectMapper;
    4. import org.springframework.cache.annotation.CachingConfigurerSupport;
    5. import org.springframework.context.annotation.Bean;
    6. import org.springframework.context.annotation.Configuration;
    7. import org.springframework.data.redis.connection.RedisConnectionFactory;
    8. import org.springframework.data.redis.core.RedisTemplate;
    9. import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
    10. import org.springframework.data.redis.serializer.StringRedisSerializer;
    11. /**
    12. * @ClassName: RedisConfig
    13. * @Description redis序列化配置
    14. * @author 月夜烛峰
    15. * @date 2022/9/13 18:47
    16. */
    17. @Configuration
    18. public class RedisConfig extends CachingConfigurerSupport {
    19. /**
    20. * 重新定义redisTemplate序列化方式
    21. * @param factory
    22. * @return
    23. */
    24. @Bean
    25. public RedisTemplate redisTemplate(RedisConnectionFactory factory) {
    26. RedisTemplate template = new RedisTemplate();
    27. template.setConnectionFactory(factory);
    28. Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
    29. ObjectMapper om = new ObjectMapper();
    30. om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
    31. jackson2JsonRedisSerializer.setObjectMapper(om);
    32. StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
    33. // key采用String的序列化方式
    34. template.setKeySerializer(stringRedisSerializer);
    35. // hash的key也采用String的序列化方式
    36. template.setHashKeySerializer(stringRedisSerializer);
    37. // value序列化方式采用jackson
    38. template.setValueSerializer(jackson2JsonRedisSerializer);
    39. // hash的value序列化方式采用jackson
    40. template.setHashValueSerializer(jackson2JsonRedisSerializer);
    41. template.afterPropertiesSet();
    42. return template;
    43. }
    44. }
    45. 重新运行项目:

      变化:

      key和value都没有了前缀

      key通过String格式进行序列化,显示正常。

      value通过jackson方式序列化,显示序列化后结果。

      value也可以不做序列化处理,但容易出现安全隐患,例如:信息泄露。 

      六、工具类改造

      在使用过程中,有时候使用RedisTemplate不是很方便,尤其是一些静态方法,所以可以把RedisTemplate进行改造,封装到静态工具类中。

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

        1. package com.zhufeng.base.redis;
        2. import org.springframework.beans.BeansException;
        3. import org.springframework.context.ApplicationContext;
        4. import org.springframework.context.ApplicationContextAware;
        5. import org.springframework.stereotype.Component;
        6. /**
        7. * @ClassName: SpringContextUtil
        8. * @Description 获取spring上下文信息
        9. * @author 月夜烛峰
        10. * @date 2022/9/13 18:18
        11. */
        12. @Component
        13. public class SpringContextUtil implements ApplicationContextAware {
        14. private static ApplicationContext applicationContext = null;
        15. @Override
        16. public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        17. if (SpringContextUtil.applicationContext == null) {
        18. SpringContextUtil.applicationContext = applicationContext;
        19. }
        20. }
        21. //获取applicationContext
        22. public static ApplicationContext getApplicationContext() {
        23. return applicationContext;
        24. }
        25. //通过name获取 Bean.
        26. public static Object getBean(String name) {
        27. return getApplicationContext().getBean(name);
        28. }
        29. //通过class获取Bean.
        30. public static T getBean(Class clazz) {
        31. return getApplicationContext().getBean(clazz);
        32. }
        33. //通过name,以及Clazz返回指定的Bean
        34. public static T getBean(String name, Class clazz) {
        35. return getApplicationContext().getBean(name, clazz);
        36. }
        37. }

        测试:

        1. @RequestMapping("redis")
        2. public Object showRedis(){
        3. redisTemplate.opsForValue().set("zhufeng-test", "测试");
        4. //return redisTemplate.opsForValue().get("zhufeng-test");
        5. return ZFRedisUtil.get("zhufeng-test");
        6. }

        可以正常获取value。

        七、注意事项

        RedisTemplate使用起来虽然非常方便,但是在高并发场景下需要做一些性能优化,一般项目使用时,没什么问题。

         

      551. 相关阅读:
        量化交易的相对强弱(RSI )指标计算及策略
        Shiro-集成验证码
        JVM 重要知识梳理
        Linux应用开发 - 多线程编程
        [论文笔记] MapReduce: Simplified Data Processing on Large Clusters
        OpenGL 摄像机视角详解
        HDD-FAT32 ZIP-FAT32 HDD-FAT16 ZIP-FAT16 HDD-NTFS
        MYSQL第一章节DDL数据定义语言的操作(DDL-数据库操作,DDL-操作表-查询,DDL-操作表-修改,数据库的基本类型)
        HtmlUnit、Jsoup、webmagic基本介绍
        八数码问题
      552. 原文地址:https://blog.csdn.net/yueyezhufeng/article/details/126846694