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依赖包

 <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</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配置类

 package ooh.chaos.configuration;

 import ooh.chaos.configuration.FastJsonRedisSerializer;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer; import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.session.SessionRepository;
import org.springframework.session.data.redis.RedisOperationsSessionRepository; /**
* redis 配置
*/
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport { @Bean
@Override
public KeyGenerator keyGenerator() {
return (target, method, params) -> {
StringBuilder sb = new StringBuilder();
sb.append(target.getClass().getName());
sb.append(method.getName());
for (Object obj : params) {
sb.append(obj.toString());
}
return sb.toString();
};
} /**
* 设置 redisTemplate 序列化方式
*
* @param factory
* @return
*/
@Bean
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<Object, Object>();
redisTemplate.setConnectionFactory(factory);
// 设置值(value)的序列化采用FastJsonRedisSerializer。
FastJsonRedisSerializer<Object> fastJsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class);
redisTemplate.setValueSerializer(fastJsonRedisSerializer);
redisTemplate.setHashValueSerializer(fastJsonRedisSerializer);
// 设置键(key)的序列化采用StringRedisSerializer。
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setDefaultSerializer(fastJsonRedisSerializer);
redisTemplate.afterPropertiesSet();
return redisTemplate;
} /**
* 设置spring session redis 序列化方式
*
* @param factory
* @return
*/
@Bean
public SessionRepository sessionRepository(RedisConnectionFactory factory) {
RedisOperationsSessionRepository sessionRepository = new RedisOperationsSessionRepository(
redisTemplate(factory));
FastJsonRedisSerializer<Object> fastJsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class);
sessionRepository.setDefaultSerializer(fastJsonRedisSerializer);
sessionRepository.setDefaultMaxInactiveInterval(36000);
return sessionRepository;
} }

最后一步:在SpringBoot项目中使用redis

1.引入redis操作bean

 @Autowired
private RedisTemplate<Object, Object> redisTemplate;

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

 // 增加token逻辑,Created by xiaoshiyilang on 2018/10/19
String md5Key = DigestUtils.md5Hex(Constants.TOKEN_KEY_PRE + user.getUid());
if (redisTemplate.opsForValue().get(md5Key) != null) {
redisTemplate.delete(md5Key);
}
String md5Token = DigestUtils.md5Hex(generalToken() + user.getUid());
if (redisTemplate.opsForValue().get(md5Token) != null) {
  redisTemplate.delete(md5Token);
}
// 返回给前端的Token
redisTemplate.opsForValue().set(md5Key, md5Token);
// 设置Token过期时间
redisTemplate.expire(md5Key, 86400 * 30, TimeUnit.SECONDS);
// 记录成功的用户id
redisTemplate.opsForValue().set(md5Token, user.getUid());
// 设置登录用户过期时间
redisTemplate.expire(md5Token, 86400 * 30, TimeUnit.SECONDS);

另一种使用方式:自动根据方法生成缓存

 @Cacheable(value = "user-key")
public User getUser(Long id) {
User user = userService.selectByPrimaryKey(id);
System.out.println("若下面没出现“无缓存的时候调用”字样且能打印出数据表示测试成功");
return user;
}

其中value的值就是缓存到redis中的key。

SpringBoot下使用Redis实现session共享

分布式系统中,session会面临需要在多个项目中共享的问题,包括集群,负载均衡也是需要session共享的,有很多的解决方案,其中托管到redis这样的缓存中是最常用的方案之一,小Alan在这里也和大家聊一聊

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

 <dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>

第二步:添加session的Java配置类

 package com.only.tech.user.configuration;

 import org.springframework.context.annotation.Configuration;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession; /**
* session配置,30分钟过期
*/
@Configuration
@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 60 * 30)
public class SessionConfig { }

maxInactiveIntervalInSeconds: 设置Session失效时间,使用Redis Session之后,原Boot的server.session.timeout属性不再生效。

最后一步:测试session是否生效

添加测试方法获取sessionid

 @RequestMapping("/uid")
String uid(HttpSession session) {
UUID uid = (UUID) session.getAttribute("uid");
if (uid == null) {
uid = UUID.randomUUID();
}
session.setAttribute("uid", uid);
return session.getId();
}

登录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

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

SpringBoot中redis的使用介绍的更多相关文章

  1. SpringBoot中Redis的set、map、list、value、实体类等基本操作介绍

    今天给大家介绍一下SpringBoot中Redis的set.map.list.value等基本操作的具体使用方法 上一节中给大家介绍了如何在SpringBoot中搭建Redis缓存数据库,这一节就针对 ...

  2. springboot中redis取缓存类型转换异常

    异常如下: [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested ...

  3. ③SpringBoot中Redis的使用

    本文基于前面的springBoot系列文章进行学习,主要介绍redis的使用. SpringBoot对常用的数据库支持外,对NoSQL 数据库也进行了封装自动化. redis介绍 Redis是目前业界 ...

  4. SpringBoot中Redis的使用

    转载:http://www.ityouknow.com/springboot/2016/03/06/spring-boot-redis.html Spring Boot 对常用的数据库支持外,对 No ...

  5. 1.2_springboot2.x中redis缓存&原理介绍

    1.整合redis作为缓存 说明这里springboot版本2.19 Redis 是一个开源(BSD许可)的,内存中的数据结构存储系统,它可以用作数据库.缓存和消息中间件. 它支持多种类型的数据结构 ...

  6. springboot中redis的缓存穿透问题

    什么是缓存穿透问题?? 我们使用redis是为了减少数据库的压力,让尽量多的请求去承压能力比较大的redis,而不是数据库.但是高并发条件下,可能会在redis还没有缓存的时候,大量的请求同时进入,导 ...

  7. springBoot 中redis 注解缓存的使用

    1,首先在启动类上加上 @EnableCaching 这个注解 在查询类的controller,或service ,dao 中方法上加 @Cacheable 更新或修改方法上加 @CachePut 注 ...

  8. springboot中redis做缓存时的配置

    import com.google.common.collect.ImmutableMap;import org.slf4j.Logger;import org.slf4j.LoggerFactory ...

  9. springboot中Redis的Lettuce客户端和jedis客户端

    1.引入客户端依赖 <!--jedis客户端依赖--> <dependency> <groupId>redis.clients</groupId> &l ...

随机推荐

  1. Selenium自动化测试Python二:WebDriver基础

    WebDriver基础 欢迎阅读WebDriver基础讲义.本篇讲义将会重点介绍Selenium WebDriver的环境搭建和基本使用方法. WebDriver环境搭建 Selenium WebDr ...

  2. sftp命令不被识别

    sftp命令不被识别 原因:C:\Windows\System32文件夹下面没有sftp可执行程序 解决方案:安装openssh,安装完成之后可发现在path系统变量的值中多了openssh的安装目录 ...

  3. Azure Redis 缓存使用注意事项与排查问题文档整理

    StackExchange.Redis 使用名为 synctimeout 的配置设置进行同步操作,该设置的默认值为 1000 毫秒. 如果同步调用未在规定时间内完成,StackExchange.Red ...

  4. Android Design Support Library——Navigation View

    前沿 Android 从5.0开始引入了Material design元素的设计,这种新的设计语言让整个安卓的用户体验焕然一新,google在Android Design Support Librar ...

  5. Css相关用法个人总结

    Css相关用法个人总结

  6. 并发编程之 Semaphore 源码分析

    前言 并发 JUC 包提供了很多工具类,比如之前说的 CountDownLatch,CyclicBarrier ,今天说说这个 Semaphore--信号量,关于他的使用请查看往期文章并发编程之 线程 ...

  7. Array.prototype.map()和Array.prototypefilter()

    ES5 => 筛选功能  Array.prototypefilter(): 代码: var words = ['spray', 'limit', 'elite', 'exuberant', 'd ...

  8. 微信小程序开源Demo精选

    来自:http://www.jianshu.com/p/0ecf5aba79e1 文/weapphome(简书作者)原文链接:http://www.jianshu.com/p/0ecf5aba79e1 ...

  9. gulp自动添加版本号过程中的一些要点记录

    1.打开node_modules\gulp-rev\index.js 第144行 manifest[originalFile] = revisionedFile; 更新为: manifest[orig ...

  10. Linux CentOS Nginx安装配置

    Nginx("engine x")是一款是由俄罗斯的程序设计师Igor Sysoev所开发高性能的 Web和 反向代理 服务器,也是一个 IMAP/POP3/SMTP 代理服务器. ...