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. PEP_2007相关问题记录

    1.在C++中,int main(int argc, char** argv)中的参数是什么意思? 其中,第一个argc是输入的参数的个数,第二个argv可以理解为一个数组,我们可以通过argv来打印 ...

  2. Composite组合模式(结构型模式)

    1.概述 在面向对象系统中,经常会遇到一些具有"容器性质"的对象,它们自己在充当容器的同时,也充当其他对象的容器. 2.案例 需要构建一个容器系统,需要满足以下几点要求: (1). ...

  3. Apache Oltu 实现 OAuth2.0 服务端【授权码模式(Authorization Code)】

    要实现OAuth服务端,就得先理解客户端的调用流程,服务提供商实现可能也有些区别,实现OAuth服务端的方式很多,具体可能看 http://oauth.net/code/ 各语言的实现有(我使用了Ap ...

  4. CentOS 7.3.1611编译安装Nginx1.10.3+MySQL5.7.16+PHP7.1.2

    前传: 1.CentOS 7.3.1611系统安装配置图解教程 http://www.jb51.net/os/RedHat/597874.html 2.CentOS服务器初始化设置 http://ww ...

  5. CentOS Java C JNI

    使用JNI调用本地代码,整个开发流程主要包括以下几个步骤: 1.创建一个Java类(IntArray.java): 2.使用javac编译该类(生成IntArray.class): 3.使用javah ...

  6. 【IT笔试面试题整理】堆栈和队列

    如何准备: Whether you are asked to implement a simple stack / queue, or you are asked to implementa modi ...

  7. rails中accepts_nested_attributes_for应用

    Model: class Blog < ActiveRecord::Base has_many :strip_rules accepts_nested_attributes_for :strip ...

  8. PHP7最高性能优化建议

    PHP7已经发布了, 作为PHP10年来最大的版本升级, 最大的性能升级, PHP7在多放的测试中都表现出很明显的性能提升, 然而, 为了让它能发挥出最大的性能, 我还是有几件事想提醒下. PHP7 ...

  9. FFmpeg简易播放器的实现-音视频播放

    本文为作者原创,转载请注明出处:https://www.cnblogs.com/leisure_chn/p/10235926.html 基于FFmpeg和SDL实现的简易视频播放器,主要分为读取视频文 ...

  10. UVA 11134 Fabled Rooks(贪心的妙用+memset误用警示)

    题目链接: https://cn.vjudge.net/problem/UVA-11134 /* 问题 输入棋盘的规模和车的数量n(1=<n<=5000),接着输入n辆车的所能在的矩阵的范 ...