SpringBoot中redis的使用介紹

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

Redis是一個開源的使用ANSI C語言編寫、遵照BSD協議、支持網絡、可基於內存亦可持久化的日誌型、Key-Value數據庫,並提供多種語言的API。web

它一般被稱爲數據結構服務器,由於值(value)能夠是 字符串(String), 哈希(Map), 列表(list), 集合(sets) 和 有序集合(sorted sets)等類型。redis

Redis是目前行業使用最普遍的內存數據存儲。比memcached更受歡迎,Redis支持更豐富的數據結構,同時支持數據持久化。spring

除此以外,Redis還提供一些類數據庫的特性,好比事務,HA,主從庫。能夠說Redis兼具了緩存系統和數據庫的一些特性,所以有着豐富的應用場景。數據庫

 

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

第一步:引入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

博客地址:http://www.cnblogs.com/AlanLee

本文出自博客園,歡迎你們加入博客園。

相關文章
相關標籤/搜索