Spring Boot + Redis 初体验
本文测试环境: Spring Boot 2.1.4.RELEASE + Redis 5.0.4 + CentOS 7
让程序先 run 起来
安装及配置 Redis
参考: How To Install and Configure Redis on CentOS 7
新建 Spring Boot 项目并添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
添加 Redis 配置
spring:
redis:
host: 192.168.30.101
port: 6379
database: 0
# password: ******
jedis:
pool:
max-active: 10
min-idle: 0
max-idle: 6
max-wait: -1
测试代码
@Component
public class StringRunner implements CommandLineRunner {
@Autowired
private StringRedisTemplate redisTemplate;
// private RedisTemplate<String, String> redisTemplate;
@Override
public void run(String... args) throws Exception {
String key;
// String: 字符串
System.out.println("====== String ======");
key = "string:string";
redisTemplate.opsForValue().set(key, "string.string", 10, TimeUnit.SECONDS);
redisTemplate.opsForValue().append(key, ".append");
System.out.println(redisTemplate.opsForValue().get(key));
key = "string:number";
redisTemplate.delete(key);
redisTemplate.opsForValue().increment(key);
redisTemplate.opsForValue().decrement(key);
System.out.println(redisTemplate.opsForValue().get(key));
// Hash: 哈希
System.out.println("====== Hash ======");
key = "hash:test";
redisTemplate.delete(key);
redisTemplate.opsForHash().put(key, "key1", "value1");
Map<String, String> map = new HashMap<>();
map.put("key2", "value2");
map.put("key3", "1");
redisTemplate.opsForHash().putAll(key, map);
System.out.println(redisTemplate.opsForHash().entries(key));
System.out.println(redisTemplate.opsForHash().keys(key));
System.out.println(redisTemplate.opsForHash().values(key));
System.out.println(redisTemplate.opsForHash().get(key, "key1"));
System.out.println(redisTemplate.opsForHash().increment(key, "key3", 1L));
redisTemplate.opsForHash().delete(key, "key2");
// List: 列表
System.out.println("====== List ======");
key = "list:test";
redisTemplate.delete(key);
redisTemplate.opsForList().rightPush(key, "1");
redisTemplate.opsForList().leftPush(key, "2");
redisTemplate.opsForList().rightPushAll(key, new String[]{"3", "4", "5"});
List<String> list = redisTemplate.opsForList().range(key, 0, -1);
for(String item : list){
System.out.print(item + ", ");
}
System.out.println();
// Set: 集合
System.out.println("====== Set ======");
key = "set:test";
String key1 = "set:test1";
String key2 = "set:test2";
redisTemplate.delete(key1);
redisTemplate.delete(key2);
redisTemplate.opsForSet().add(key1, "value1", "value2", "value1-1", "value1-2");
System.out.println(redisTemplate.opsForSet().members(key1));
redisTemplate.opsForSet().remove(key1, "value1-1");
redisTemplate.opsForSet().move(key1, "value1", key2);
redisTemplate.opsForSet().add(key2, "value2");
System.out.println(redisTemplate.opsForSet().intersect(key1, key2));// 交集
redisTemplate.opsForSet().intersectAndStore(key1, key2, key);// 交集
System.out.println(redisTemplate.opsForSet().members(key));
System.out.println(redisTemplate.opsForSet().union(key1, key2));// 并集
System.out.println(redisTemplate.opsForSet().difference(key1, Arrays.asList(key2)));// 差集
// zset (sorted set): 有序集合
// 与 Set 类似,略
}
}

更进一步
上文中我们与 Redis 交互使用的是 Spring 封装的 StringRedisTemplate, 源码:
public class StringRedisTemplate extends RedisTemplate<String, String> {
public StringRedisTemplate() {
this.setKeySerializer(RedisSerializer.string());
this.setValueSerializer(RedisSerializer.string());
this.setHashKeySerializer(RedisSerializer.string());
this.setHashValueSerializer(RedisSerializer.string());
}
public StringRedisTemplate(RedisConnectionFactory connectionFactory) {
this();
this.setConnectionFactory(connectionFactory);
this.afterPropertiesSet();
}
protected RedisConnection preProcessConnection(RedisConnection connection, boolean existingConnection) {
return new DefaultStringRedisConnection(connection);
}
}
可以看到 StringRedisTemplate 继承自 RedisTemplate 并在构造函数中设置了 key 和 value 的 Serializer (RedisTemplate 默认使用的是 JdkSerializationRedisSerializer, 在 RedisTemplate 源码中可以看到)
RedisSerializer 源码:
public interface RedisSerializer<T> {
@Nullable
byte[] serialize(@Nullable T var1) throws SerializationException;
@Nullable
T deserialize(@Nullable byte[] var1) throws SerializationException;
static RedisSerializer<Object> java() {
return java((ClassLoader)null);
}
static RedisSerializer<Object> java(@Nullable ClassLoader classLoader) {
return new JdkSerializationRedisSerializer(classLoader);
}
static RedisSerializer<Object> json() {
return new GenericJackson2JsonRedisSerializer();
}
static RedisSerializer<String> string() {
return StringRedisSerializer.UTF_8;
}
}
Spring 同时也封装了几种 Serializer, 如 JdkSerializationRedisSerializer, GenericJackson2JsonRedisSerializer, StringRedisSerializer 等,详见下图:

自定义 RedisTemplate
添加依赖
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.8</version>
</dependency>
配置 Serializer
下面代码分别使用了 GenericJackson2JsonRedisSerializer 和 Jackson2JsonRedisSerializer
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory){
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(factory);
template.setKeySerializer(RedisSerializer.string());
template.setHashKeySerializer(RedisSerializer.string());
// 使用 GenericJackson2JsonRedisSerializer
template.setValueSerializer(RedisSerializer.json());
template.setHashValueSerializer(RedisSerializer.json());
// 使用 Jackson2JsonRedisSerializer
// Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
// ObjectMapper objectMapper = new ObjectMapper();
// objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
// objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
// jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
//
// template.setValueSerializer(jackson2JsonRedisSerializer);
// template.setHashValueSerializer(jackson2JsonRedisSerializer);
return template;
}
}
测试
@Component
public class ObjectRunner implements CommandLineRunner {
@Autowired
private RedisTemplate redisTemplate;
@Override
public void run(String... args) throws Exception {
String key;
System.out.println("====== Object ======");
User user = new User();
user.setId(1);
user.setName("admin");
key = "user:id:" + user.getId();
redisTemplate.opsForValue().set(key, user);
user = (User)redisTemplate.opsForValue().get(key);
System.out.println(user.getName());
}
}
P.S. 用冒号作为分割在 Redis 中是设计 key 的一种不成文原则
源码:GitHub
本人 C# 转 Java 的 newbie, 如果错误或不足欢迎指正,谢谢
参考:
- springboot 整合redis(自定义RedisTemplate)
- RedisTemplate中hash类型的使用
- RedisTemplate中set类型的使用
- RedisTemplate中zset类型的使用
Spring Boot + Redis 初体验的更多相关文章
- Spring boot缓存初体验
spring boot缓存初体验 1.项目搭建 使用MySQL作为数据库,spring boot集成mybatis来操作数据库,所以在使用springboot的cache组件时,需要先搭建一个简单的s ...
- spring boot redis缓存JedisPool使用
spring boot redis缓存JedisPool使用 添加依赖pom.xml中添加如下依赖 <!-- Spring Boot Redis --> <dependency> ...
- spring boot + redis 实现session共享
这次带来的是spring boot + redis 实现session共享的教程. 在spring boot的文档中,告诉我们添加@EnableRedisHttpSession来开启spring se ...
- Spring Boot 项目学习 (三) Spring Boot + Redis 搭建
0 引言 本文主要介绍 Spring Boot 中 Redis 的配置和基本使用. 1 配置 Redis 1. 修改pom.xml,添加Redis依赖 <!-- Spring Boot Redi ...
- Spring Boot Redis 集成配置(转)
Spring Boot Redis 集成配置 .embody{ padding:10px 10px 10px; margin:0 -20px; border-bottom:solid 1px #ede ...
- spring boot redis 缓存(cache)集成
Spring Boot 集成教程 Spring Boot 介绍 Spring Boot 开发环境搭建(Eclipse) Spring Boot Hello World (restful接口)例子 sp ...
- Spring boot集成redis初体验
pom.xml: <?xml version="1.0" encoding="UTF-8"?> <project xmlns="ht ...
- 215.Spring Boot+Spring Security:初体验
[视频&交流平台] SpringBoot视频:http://t.cn/R3QepWG Spring Cloud视频:http://t.cn/R3QeRZc SpringBoot Shiro视频 ...
- spring boot redis分布式锁
随着现在分布式架构越来越盛行,在很多场景下需要使用到分布式锁.分布式锁的实现有很多种,比如基于数据库. zookeeper 等,本文主要介绍使用 Redis 做分布式锁的方式,并封装成spring b ...
随机推荐
- 7 apache和nginx的区别
7 apache和nginx的区别 nginx 相对 apache 的优点: 轻量级,同样起web 服务,比apache 占用更少的内存及资源 抗并发,nginx 处理请求是异步非阻塞的,支持更多的并 ...
- 快速了解阿里微服务热门开源分布式事务框架——Seata
一.Seata 概述 Seata 是 Simple Extensible Autonomous Transaction Architecture 的简写,由 feascar 改名而来. Seata 是 ...
- 机器学习-logistic对数回归求参数,画散点图以及分割线
这个在我初学的时候我也不是很明白,于是在查了很多资料后找到一个很不错的博客给大家分享一下!! 研读一下代码对初学者有很大的帮助 作为一个初学者,一开始都是模仿别人的代码学会后就成为自己的东西了,相信你 ...
- nginx&http 第二章 ngx 事件event配置等初始化
event事件模块,配置分为两层:ngx_events_module 事件模块 和 ngx_event_core_module 事件核心模块.ngx_events_module:模块类型NGX_COR ...
- shell编程之俄罗斯方块
按键获取: 向上 ^[[A 向下 ^[[B 向左 ^[[D 向右 ^[[C 其中 ^[为ESC键. 按键获取的具体shell代码如下所示: #! /bin/bash GetKey() { a ...
- Python的ConfigParser模块读取ini配置文件 报错(持续更新总结)
1.ConfigParser.MissingSection什么的错误巴拉巴拉一堆,其实根本上就是没有读到配置文件,然后我去检查了一遍路径,发现没有问题,我是将文件的路径作为一个字符串拼接好传到另一个专 ...
- java多线程---张孝祥
1.java web 中,一次http请求是一个任务,因为服务器里面有线程池的,存在一个线程处理多个请求任务. 2.在java中,vector,hashtable,concurrentHashMap是 ...
- python爬虫分析报告
在python课上布置的作业,第一次进行爬虫,走了很多弯路,也学习到了很多知识,借此记录. 1. 获取学堂在线合作院校页面 要求: 爬取学堂在线的计算机类课程页面内容. 要求将课程名称.老师.所属学校 ...
- 统计数字问题(Java)
Description 一本书的页码从自然数1 开始顺序编码直到自然数n.书的页码按照通常的习惯编排,每个页码都不含多余的前导数字0.例如,第6 页用数字6 表示,而不是06 或006 等.数字计数问 ...
- 整理了 15 道 Spring Boot 高频面试题,看完当面霸!
转载:https://mp.weixin.qq.com/s/fj-DeDfGcIAs8jQbs6bbPA 什么是面霸?就是在面试中,神挡杀神佛挡杀佛,见招拆招,面到面试官自惭形秽自叹不如!松哥希望本文 ...