1. 程式人生 > >SpringBoot中redis的使用介紹

SpringBoot中redis的使用介紹

REmote DIctionary Server(Redis) 是一個由Salvatore Sanfilippo寫的key-value儲存系統。

Redis是一個開源的使用ANSI C語言編寫、遵守BSD協議、支援網路、可基於記憶體亦可持久化的日誌型、Key-Value資料庫,並提供多種語言的API。

它通常被稱為資料結構伺服器,因為值(value)可以是 字串(String), 雜湊(Map), 列表(list), 集合(sets) 和 有序集合(sorted sets)等型別。

Redis是目前行業使用最廣泛的記憶體資料儲存。比memcached更受歡迎,Redis支援更豐富的資料結構,同時支援資料持久化。

除此之外,Redis還提供一些類資料庫的特性,比如事務,HA,主從庫。可以說Redis兼具了快取系統和資料庫的一些特性,因此有著豐富的應用場景。

今天,小Alan和大家聊一下redis在SpringBoot2.0版本後如何使用

第一步:引入spring-boot-starter-data-redis依賴包

1 <dependency>
2     <groupId>org.springframework.boot</groupId>
3     <artifactId>spring-boot-starter-data-redis</artifactId
> 4 </dependency>

第二步:編寫配置檔案application.yml(當然,也可以通過profile機制指向不同的環境配置檔案)

spring:
  # profiles:
  #  active: dev
  redis:
    database: 0
    host: www.weiyi.com
    password: null
    max-active: 8
    max-idle: 500
    max-wait: 1
    min-idle: 0
    port: 6379
    timeout: 5000ms

第三步:新增redis的Java配置類

 1 package ooh.chaos.configuration;
 2 
 3 import ooh.chaos.configuration.FastJsonRedisSerializer;
 4 import org.springframework.cache.annotation.CachingConfigurerSupport;
 5 import org.springframework.cache.annotation.EnableCaching;
 6 import org.springframework.context.annotation.Bean;
 7 import org.springframework.context.annotation.Configuration;
 8 import org.springframework.data.redis.connection.RedisConnectionFactory;
 9 import org.springframework.data.redis.core.RedisTemplate;
10 import org.springframework.data.redis.serializer.StringRedisSerializer;
11 
12 import org.springframework.cache.interceptor.KeyGenerator;
13 import org.springframework.session.SessionRepository;
14 import org.springframework.session.data.redis.RedisOperationsSessionRepository;
15 
16 /**
17  * redis 配置
18  */
19 @Configuration
20 @EnableCaching
21 public class RedisConfig extends CachingConfigurerSupport {
22 
23     @Bean
24     @Override
25     public KeyGenerator keyGenerator() {
26         return (target, method, params) -> {
27             StringBuilder sb = new StringBuilder();
28             sb.append(target.getClass().getName());
29             sb.append(method.getName());
30             for (Object obj : params) {
31                 sb.append(obj.toString());
32             }
33             return sb.toString();
34         };
35     }
36 
37     /**
38      * 設定 redisTemplate 序列化方式
39      *
40      * @param factory
41      * @return
42      */
43     @Bean
44     public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory factory) {
45         RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<Object, Object>();
46         redisTemplate.setConnectionFactory(factory);
47         // 設定值(value)的序列化採用FastJsonRedisSerializer。
48         FastJsonRedisSerializer<Object> fastJsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class);
49         redisTemplate.setValueSerializer(fastJsonRedisSerializer);
50         redisTemplate.setHashValueSerializer(fastJsonRedisSerializer);
51         // 設定鍵(key)的序列化採用StringRedisSerializer。
52         redisTemplate.setKeySerializer(new StringRedisSerializer());
53         redisTemplate.setHashKeySerializer(new StringRedisSerializer());
54         redisTemplate.setDefaultSerializer(fastJsonRedisSerializer);
55         redisTemplate.afterPropertiesSet();
56         return redisTemplate;
57     }
58 
59     /**
60      * 設定spring session redis 序列化方式
61      *
62      * @param factory
63      * @return
64      */
65     @Bean
66     public SessionRepository sessionRepository(RedisConnectionFactory factory) {
67         RedisOperationsSessionRepository sessionRepository = new RedisOperationsSessionRepository(
68                 redisTemplate(factory));
69         FastJsonRedisSerializer<Object> fastJsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class);
70         sessionRepository.setDefaultSerializer(fastJsonRedisSerializer);
71         sessionRepository.setDefaultMaxInactiveInterval(36000);
72         return sessionRepository;
73     }
74 
75 }

最後一步:在SpringBoot專案中使用redis

1.引入redis操作bean

1 @Autowired
2 private RedisTemplate<Object, Object> redisTemplate;

2.使用redisTemplate操作redis,手動使用方式

 1 // 增加token邏輯,Created by xiaoshiyilang on 2018/10/19
 2 String md5Key = DigestUtils.md5Hex(Constants.TOKEN_KEY_PRE + user.getUid());
 3 if (redisTemplate.opsForValue().get(md5Key) != null) {
 4     redisTemplate.delete(md5Key);
 5 }
 6 String md5Token = DigestUtils.md5Hex(generalToken() + user.getUid());
 7 if (redisTemplate.opsForValue().get(md5Token) != null) {
 8   redisTemplate.delete(md5Token);
 9 }
10 // 返回給前端的Token
11 redisTemplate.opsForValue().set(md5Key, md5Token);
12 // 設定Token過期時間
13 redisTemplate.expire(md5Key, 86400 * 30, TimeUnit.SECONDS);
14 // 記錄成功的使用者id
15 redisTemplate.opsForValue().set(md5Token, user.getUid());
16 // 設定登入使用者過期時間
17 redisTemplate.expire(md5Token, 86400 * 30, TimeUnit.SECONDS);

另一種使用方式:自動根據方法生成快取

1 @Cacheable(value = "user-key")
2 public User getUser(Long id) {
3     User user = userService.selectByPrimaryKey(id);
4     System.out.println("若下面沒出現“無快取的時候呼叫”字樣且能打印出資料表示測試成功");
5     return user;
6 }

其中value的值就是快取到redis中的key。

SpringBoot下使用Redis實現session共享

分散式系統中,session會面臨需要在多個專案中共享的問題,包括叢集,負載均衡也是需要session共享的,有很多的解決方案,其中託管到redis這樣的快取中是最常用的方案之一,小Alan在這裡也和大家聊一聊

第一步:引入spring-session-data-redis依賴包

1 <dependency>
2         <groupId>org.springframework.session</groupId>
3         <artifactId>spring-session-data-redis</artifactId>
4 </dependency>

第二步:新增session的Java配置類

 1 package com.only.tech.user.configuration;
 2 
 3 import org.springframework.context.annotation.Configuration;
 4 import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
 5 
 6 /**
 7  * session配置,30分鐘過期
 8  */
 9 @Configuration
10 @EnableRedisHttpSession(maxInactiveIntervalInSeconds = 60 * 30)
11 public class SessionConfig {
12 
13 }

maxInactiveIntervalInSeconds: 設定Session失效時間,使用Redis Session之後,原Boot的server.session.timeout屬性不再生效。

最後一步:測試session是否生效

新增測試方法獲取sessionid

1 @RequestMapping("/uid")
2 String uid(HttpSession session) {
3         UUID uid = (UUID) session.getAttribute("uid");
4         if (uid == null) {
5             uid = UUID.randomUUID();
6         }
7         session.setAttribute("uid", uid);
8         return session.getId();
9 }

登入redis客戶端檢視是否儲存sessionid相關的值

訪問瀏覽器執行多個請求如果是同一個sessionid就說明session已經在redis中進行有效的管理了。

如何在兩個專案或者多個專案中共享session(或者多臺機器)

按照上面的步驟在另一個專案中再次配置一次session,啟動專案後自動就進行了session的共享機制。

注意:我在redis的Java配置類中設定了spring session redis 的序列化方式,因為我這裡沒有使用SpringBoot預設的json序列化方式,而是使用了阿里的fastjson。

結束語:這城市總是風很大,孤獨的人晚回家,外面不像你想的那麼好,風雨都要直接擋。願每個獨自走夜路的你,都足夠堅強。

佛系博主:AlanLee

本文出自部落格園,歡迎大家加入部落格園。