本文测试环境: 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, 如果错误或不足欢迎指正,谢谢

参考:

Spring Boot + Redis 初体验的更多相关文章

  1. Spring boot缓存初体验

    spring boot缓存初体验 1.项目搭建 使用MySQL作为数据库,spring boot集成mybatis来操作数据库,所以在使用springboot的cache组件时,需要先搭建一个简单的s ...

  2. spring boot redis缓存JedisPool使用

    spring boot redis缓存JedisPool使用 添加依赖pom.xml中添加如下依赖 <!-- Spring Boot Redis --> <dependency> ...

  3. spring boot + redis 实现session共享

    这次带来的是spring boot + redis 实现session共享的教程. 在spring boot的文档中,告诉我们添加@EnableRedisHttpSession来开启spring se ...

  4. Spring Boot 项目学习 (三) Spring Boot + Redis 搭建

    0 引言 本文主要介绍 Spring Boot 中 Redis 的配置和基本使用. 1 配置 Redis 1. 修改pom.xml,添加Redis依赖 <!-- Spring Boot Redi ...

  5. Spring Boot Redis 集成配置(转)

    Spring Boot Redis 集成配置 .embody{ padding:10px 10px 10px; margin:0 -20px; border-bottom:solid 1px #ede ...

  6. spring boot redis 缓存(cache)集成

    Spring Boot 集成教程 Spring Boot 介绍 Spring Boot 开发环境搭建(Eclipse) Spring Boot Hello World (restful接口)例子 sp ...

  7. Spring boot集成redis初体验

    pom.xml: <?xml version="1.0" encoding="UTF-8"?> <project xmlns="ht ...

  8. 215.Spring Boot+Spring Security:初体验

    [视频&交流平台] SpringBoot视频:http://t.cn/R3QepWG Spring Cloud视频:http://t.cn/R3QeRZc SpringBoot Shiro视频 ...

  9. spring boot redis分布式锁

    随着现在分布式架构越来越盛行,在很多场景下需要使用到分布式锁.分布式锁的实现有很多种,比如基于数据库. zookeeper 等,本文主要介绍使用 Redis 做分布式锁的方式,并封装成spring b ...

随机推荐

  1. 排序算法—快速排序(Quick Sort)

    快速排序(Quick Sort) 快速排序的基本思想:通过一趟排序将待排记录分隔成独立的两部分,其中一部分记录的关键字均比另一部分的关键字小,则可分别对这两部分记录继续进行排序,以达到整个序列有序. ...

  2. How to using code post packingSlip on Quality Orders Form[AX2009]

    For simple user operation posting packing slip with purchase order. we added a function button on Qu ...

  3. 16、Auth认证组件

    1 Auth模块是什么 Auth模块是Django自带的用户认证模块: 我们在开发一个网站的时候,无可避免的需要设计实现网站的用户系统.此时我们需要实现包括用户注册.用户登录.用户认证.注销.修改密码 ...

  4. 0 quickstart

    说明 使用的安装包有: Prism 6.3 Unity 4.0.1 基于Prism框架的应用程序都包含一个主项目和若干功能模块,主项目负责启动时初始化工作,包括依赖注入容器,定义Shell等等.功能模 ...

  5. Java -- "final" 的理解

    Java具有继承和多态的特性,这也造就了Java语言的面向对象的灵活性.但是,过于灵活就意味的有失控的可能性. 于是,产生了final 的概念 -- 为了数据的绝对安全,无法被后期修改,英文称之为 m ...

  6. 腾讯云--cdn静态内容上传刷新

    一.cdn缓存刷新 当静态内容需要更新时,通常会往COS覆盖上传,不覆盖删除上传等进行更新资源或删除对象存储中的内容. 如果配置的CDN缓存过期时间较长,会导致文件更新后其他边缘节点依旧会缓存旧资源: ...

  7. Redis快速入门教程

    1.Redis介绍 Redis说白了就是个存放Key-Value数据接口的内存存储系统,主要用作数据库缓存和消息代理. 内部支持sring,hash,list,set,sorted-set五种数据结构 ...

  8. mysql上月最后一天,当月最后一天

    select last_day(DATE_SUB(now(),INTERVAL 1 MONTH)) #上月最后一天日期 %Y-%m-%d select last_day(curdate()) #当月最 ...

  9. 使用配置文件方式记录Python程序日志

    开发者可以通过三种方式配置日志记录: 调用配置方法的Python代码显式创建记录器.处理程序和格式化程序. 创建日志配置文件并使用fileConfig() 函数读取. 创建配置信息字典并将其传递给di ...

  10. 如何实现Http请求报头的自动转发[应用篇]

    如今的应用部署逐渐向微服务化发展,导致一个完整的事务往往会跨越很多的应用或服务,出于分布式链路跟踪的需要,我们往往将从上游服务获得的跟踪请求报头无脑地向下游服务进行转发.本文介绍的这个名为Header ...