Redis是一个开源的使用ANSI C语言编写、支持网络、可基于内存亦可持久化的日志型、Key-Value数据库,并提供多种语言的API。
redis是一个key-value存储系统,支持存储的value类型包括string(字符串)、list(链表)、set(集合)、zset(sorted set --有序集合)和hash(哈希类型)。

一、pom.xml引入redis模块

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

二、application.properties配置

server.port = 9001

# Redis数据库索引(默认为0)
spring.redis.database = 0
# Redis服务器地址
spring.redis.host = 127.0.0.1
# Redis服务器连接端口
spring.redis.port = 6379
# Redis服务器连接密码(如果没有则设置为空)
spring.redis.password = 123456
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active = 8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait = -1
# 连接池中的最大空闲连接
spring.redis.pool.max-idle = 8
# 连接池中的最小空闲连接
spring.redis.pool.min-idle = 0
# 连接超时时间(毫秒)
spring.redis.timeout = 1000

备注:
网上一些例子spring.redis.timeout设置为0,不能设置为0,刚开始也是照抄过来,结果报了连接超时错误
Unable to connect to Redis; nested exception is io.lettuce.core.RedisCommandTimeoutException: Command timed out

三、RedisConfig配置

代码来自:https://blog.csdn.net/lx1309244704/article/details/80696235

package com.example.demo.config;

import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Set; import javax.annotation.Resource; import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectMapper.DefaultTyping; @Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport { @Resource
private LettuceConnectionFactory lettuceConnectionFactory; @Bean
public KeyGenerator keyGenerator() {
return new KeyGenerator() {
@Override
public Object generate(Object target, Method method, Object... params) {
StringBuffer sb = new StringBuffer();
sb.append(target.getClass().getName());
sb.append(method.getName());
for (Object obj : params) {
sb.append(obj.toString());
}
return sb.toString();
}
};
} // 缓存管理器
@Bean
public CacheManager cacheManager() {
RedisCacheManager.RedisCacheManagerBuilder builder = RedisCacheManager.RedisCacheManagerBuilder.fromConnectionFactory(lettuceConnectionFactory);
@SuppressWarnings("serial")
Set<String> cacheNames = new HashSet<String>() {
{
add("codeNameCache");
}
};
builder.initialCacheNames(cacheNames);
return builder.build();
} /**
* RedisTemplate配置
*/
@Bean
public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory) {
// 设置序列化
Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, Visibility.ANY);
om.enableDefaultTyping(DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
// 配置redisTemplate
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
redisTemplate.setConnectionFactory(lettuceConnectionFactory);
RedisSerializer<?> stringSerializer = new StringRedisSerializer();
redisTemplate.setKeySerializer(stringSerializer);// key序列化
redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);// value序列化
redisTemplate.setHashKeySerializer(stringSerializer);// Hash key序列化
redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);// Hash value序列化
redisTemplate.afterPropertiesSet();
return redisTemplate;
} }

四、Redis使用例子

package com.example.demo.web.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController; @RestController
public class DemoController { @Autowired
private StringRedisTemplate stringRedisTemplate; @RequestMapping(value = "/redis", method = RequestMethod.GET)
public String redis() { stringRedisTemplate.opsForValue().set("test1", "test11111");//存入数据
String test1 = stringRedisTemplate.opsForValue().get("test1"); return test1;
} }

在浏览器访问http://localhost:9001/redis,可看到输出结果为:test11111

备注:RedisTemplate中定义了5种数据结构操作

redisTemplate.opsForValue();  //操作字符串
redisTemplate.opsForHash();   //操作hash
redisTemplate.opsForList();   //操作list
redisTemplate.opsForSet();   //操作set
redisTemplate.opsForZSet();   //操作有序set

五、单元测试

package com.example.demo;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests { @Autowired
private StringRedisTemplate stringRedisTemplate; @Test
public void contextLoads() {
} @Test
public void test1() throws Exception {
stringRedisTemplate.opsForValue().set("a", "123");
Assert.assertEquals("123", stringRedisTemplate.opsForValue().get("a"));
} }

Spring Boot 2集成Redis的更多相关文章

  1. Spring Boot 中集成 Redis 作为数据缓存

    只添加注解:@Cacheable,不配置key时,redis 中默认存的 key 是:users::SimpleKey [](1.redis-cli 中,通过命令:keys * 查看:2.key:缓存 ...

  2. Spring Boot 项目集成Redis

    目录 集成方式 使用Jedis 使用spring-data-redis Redis的安装 绑定配置 获取Redis客户端 Redis工具的编写 使用 集成方式 使用Jedis Jedis是Redis官 ...

  3. spring boot中集成Redis

    1 pom.xml文件中添加依赖 <dependency> <groupId>org.springframework.boot</groupId> <arti ...

  4. Spring Boot快速集成kaptcha生成验证码

    Kaptcha是一个非常实用的验证码生成工具,可以通过配置生成多样化的验证码,以图片的形式显示,从而无法进行复制粘贴:下面将详细介绍下Spring Boot快速集成kaptcha生成验证码的过程. 本 ...

  5. Spring Boot + MyBatis + Druid + Redis + Thymeleaf 整合小结

    Spring Boot + MyBatis + Druid + Redis + Thymeleaf 整合小结 这两天闲着没事想利用**Spring Boot**加上阿里的开源数据连接池**Druid* ...

  6. spring boot 中使用redis session

    spring boot 默认的httpsession是存在内存中.这种默认方式有几个缺点:1.当分布式部署时,存在session不一致的问题:2.当服务重启时session就会丢失,这时候用户就需要重 ...

  7. Spring Boot 2.x Redis多数据源配置(jedis,lettuce)

    Spring Boot 2.x Redis多数据源配置(jedis,lettuce) 96 不敢预言的预言家 0.1 2018.11.13 14:22* 字数 65 阅读 727评论 0喜欢 2 多数 ...

  8. Spring Boot:集成Druid数据源

    综合概述 数据库连接池负责分配.管理和释放数据库连接,它允许应用程序重复使用一个现有的数据库连接,而不是再重新建立一个:释放空闲时间超过最大空闲时间的数据库连接来避免因为没有释放数据库连接而引起的数据 ...

  9. shiro 和 spring boot 的集成

    1 添加依赖 使用 shiro-spring-boot-web-starter 在 spring boot 中集成 shiro 只需要再添加一个依赖 <dependency> <gr ...

随机推荐

  1. poj 3126 Prime Path(搜索专题)

    Prime Path Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 20237   Accepted: 11282 Desc ...

  2. 浅谈编码Base64、Hex、UTF-8、Unicode、GBK等

    网络上大多精彩的回答,该随笔用作自我总结: 首先计算机只认得二进制,0和1,所以我们现在看到的字都是经过二进制数据编码后的:计算机能针对0和1的组合做很多事情,这些规则都是人定义的:然后有了字节的概念 ...

  3. 【微信小程序——开发步骤1】

    知识点:   view,image,text编写文本框架 使用弹性盒子动态布局 使用rpx调试分辨率 在wxml中查看默认样式属性 步骤: 1.以如图页面实例说明如何写出微信文本内容 先对页面写出整体 ...

  4. Python----Windous下安装python

    一.  python 安装 1. 下载安装包 https://www.python.org/ftp/python/2.7.14/python-2.7.14.amd64.msi # 2.7安装包 htt ...

  5. CH 2401 - 送礼 - [折半DFS+二分]

    题目链接:传送门 描述 作为惩罚,GY被遣送去帮助某神牛给女生送礼物(GY:貌似是个好差事)但是在GY看到礼物之后,他就不这么认为了.某神牛有N个礼物,且异常沉重,但是GY的力气也异常的大(-_-b) ...

  6. C和C指针小记(十三)-数组

    1.1 一维数组 一维数组的声明: int a[10]; 这里a就是一个数组. 数组a的类型就是一个指向整型的常量指针. 但是数组和指针是**不相同**的. **数组具有特定数量的元素,而指针只是一个 ...

  7. Attention模型

    李宏毅深度学习 https://www.bilibili.com/video/av9770302/?p=8 Generation 生成模型基本结构是这样的, 这个生成模型有个问题是我不能干预数据生成, ...

  8. tarjan代码

    还有五天就是NOIP2018了……本蒟蒻还要复习期中考试,因此实在没有时间写博客了(各种找借口).这里就放一下代码 //Tarjan缩点 //题目描述:给一个有向图.每个点有一个权值,求权值和最大的路 ...

  9. μCOS-II移植 - 基于CortexM3

    μCOS-II是一个经典的RTOS. 任务切换对于RTOS来说是最基本也是最核心的部分,除此之外还有任务调度算法. 先来看看基于stm32f107的任务切换代码: ;***************** ...

  10. SpringMVC控制器方法参数传入的ModelMap 和Model类型有啥区别

    参考 http://blog.csdn.net/u013067598/article/details/69372309 http://blog.csdn.net/u013686993/article/ ...