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兼具了缓存系统和数据库的一些特性,因此有着丰富的应用场景。

 

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

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

GitHub地址:https://github.com/AlanLee-Java

本文出自博客园,欢迎大家加入博客园。

 

posted @ 2018-11-21 14:32  AlanLee-Java  阅读(5236)  评论(0编辑  收藏  举报