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 ...
随机推荐
- Cocos Creator 源码解读:引擎启动与主循环
前言 预备 不知道你有没有想过,假如把游戏世界比作一辆汽车,那么这辆"汽车"是如何启动,又是如何持续运转的呢? 如题,本文的内容主要为 Cocos Creator 引擎的启动流程和 ...
- 基于gin的golang web开发:访问mysql数据库
web开发基本都离不开访问数据库,在Gin中使用mysql数据库需要依赖mysql的驱动.直接使用驱动提供的API就要写很多样板代码.你可以找到很多扩展包这里介绍的是jmoiron/sqlx.另外还有 ...
- springcloud-zinpin的安装与使用
springcloud-zipkin的安装与使用 1.什么是zipkin 一个分布式系统的调用跟踪监控系统,把每次微服务调用都埋上点,打印固定格式的日志,然后收集到zipkin中,然后zipkin做数 ...
- MySQL日期函数与日期转换格式化函数大全
Mysql作为一款开元的免费关系型数据库,用户基础非常庞大,本文列出了MYSQL常用日期函数与日期转换格式化函数 1.DAYOFWEEK(date) 1 2 SELECT DAYOFWEEK('201 ...
- ubuntu下安装nginx -php
mysql : sudo apt-get install mysql-server mysql-client nginx: sudo apt-get install nginx安装Nginx稳定版本 ...
- 6 MVVM进阶
1. 背景 MVVM是一种常用的设计模式,它的最主要功能是将数据与代码隔离,实现viewmodel的可测试.架构图如下: 2. 命令-Command 2.1 WPF 路由命令 WPF提供一种内置的命令 ...
- Android序列化问题与思考
今天再来谈谈Android中的对象序列化,你了解多少呢? 序列化指的是什么?有什么用 序列化指的是讲对象变成有序的字节流,变成字节流之后才能进行传输存储等一系列操作. 反序列化就是序列化的相反操作,也 ...
- 关于mybatis拦截器,对结果集进行拦截
因业务需要,需将结果集序列化为json返回,于是,网上找了好久资料,都是关于拦截参数的处理,拦截Sql语法构建的处理,就是很少关于对拦截结果集的处理,于是自己简单的写了一个对结果集的处理, 记录下. ...
- java-Queue方法
Collection>Queue // 1. 新增 add/ offer boolean add(E e); // 队列满,IllegalStateException boolean offer ...
- 使用@Validated校验数据(除数据库做辅助)
一.controller层 /** * 使用@Validated来进行校验 * @author HuangJingNa * @date 2019年12月23日 下午6:02:20 * * @param ...