SpringBoot2.x集成Redis (StringTemplate与redisTemplate的用法)
1. Redis介绍
Redis数据库是一个完全开源免费的高性能Key-Value数据库。它支持存储的value类型有五种,包括string(字符串)、list(链表)、set(集合)、zset(sorted set –有序集合)和hash(哈希类型)
Redis非常快,每秒可执行大约110000次的设置(SET)操作,每秒大约可执行81000次的读取/获取(GET)操作。
2. 开发工具
IDEA、Maven、SpringBoot2.0.4、Jdk1.8、Redis3.2.100、PostMan
3. 配置
3.1 说明
spring 封装了两种不同的对象来进行对redis的各种操作,分别是StringTemplate与redisTemplate。
两者的关系是StringRedisTemplate继承RedisTemplate。
两者的数据是不共通的;也就是说StringRedisTemplate只能管理StringRedisTemplate里面的数据,RedisTemplate只能管理RedisTemplate中的数据。
SDR默认采用的序列化策略有两种,一种是String的序列化策略,一种是JDK的序列化策略。
StringRedisTemplate默认采用的是String的序列化策略,保存的key和value都是采用此策略序列化保存的。
RedisTemplate默认采用的是JDK的序列化策略,保存的key和value都是采用此策略序列化保存的。
其实通俗的来讲:
当你的redis数据库里面本来存的是字符串数据或者你要存取的数据就是字符串类型数据的时候,那么你就使用StringRedisTemplate即可。
但是如果你的数据是复杂的对象类型,而取出的时候又不想做任何的数据转换,直接从Redis里面取出一个对象,那么使用RedisTemplate是
更好的选择。
3.2 StringRedisTemple
Maven配置
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
yml配置文件
server:
port: 8080 spring:
application:
name: spirng-boot-redis
redis:
host: 127.0.0.1
timeout: 3000
password: 123456
port: 6379
database: 0
jedis:
pool:
max-active: 8 # 连接池最大连接数(使用负值表示没有限制)
max-idle: 8 # 连接池中的最大空闲连接
max-wait: -1 # 连接池最大阻塞等待时间(使用负值表示没有限制)
min-idle: 0 # 连接池中的最小空闲连接
Service业务实现
创建StringRedisService
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service; /**
* redis业务*/
@Service
public class StringRedisService {
private static final Logger logger = LoggerFactory.getLogger(StringRedisService.class);
@Autowired
private StringRedisTemplate stringRedisTemplate; public void setString(String key, String value){
logger.info("--------------------->[Redis set start]");
stringRedisTemplate.opsForValue().set(key,value);
} public String getString(String key){
logger.info("--------------------->[Redis get start]");
return stringRedisTemplate.opsForValue().get(key);
}
}
测试
测试代码:
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.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class)
@SpringBootTest
public class StringRedisServiceTest { @Autowired
StringRedisService stringRedisService; @Test
public void set() {
stringRedisService.setString("name","张三");
} @Test
public void get(){
System.out.println(stringRedisService.getString("name"));
}
}
3.3 RedisTemple
当我们的数据是复杂的对象类型,那么可以采用RedisTemple
手动配置
首先我们需要手动创建Redis的配置类,来自定义序列化
@Configuration
@EnableCaching
public class RedisConfiguration extends CachingConfigurerSupport {
private static final Logger logger = LoggerFactory.getLogger(RedisConfiguration.class); /**
* redis模板,存储关键字是字符串,值jackson2JsonRedisSerializer是序列化后的值
* @param
* @return org.springframework.data.redis.core.RedisTemplate*/
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(connectionFactory);
//使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
Jackson2JsonRedisSerializer 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); //使用StringRedisSerializer来序列化和反序列化redis的key值
RedisSerializer redisSerializer = new StringRedisSerializer();
//key
redisTemplate.setKeySerializer(redisSerializer);
redisTemplate.setHashKeySerializer(redisSerializer);
//value
redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer); redisTemplate.afterPropertiesSet();
return redisTemplate;
}
}
定义User实体类
注意:这里必须实现序列化接口
import java.io.Serializable;
public class User implements Serializable {
private static final long serialVersionUID = -8289770787953160443L;
private String userName;
private Integer age;
public User(String userName, Integer age) {
this.userName = userName;
this.age = age;
}
public User() {
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"userName='" + userName + '\'' +
", age=" + age +
'}';
}
}
Service方法
RedisTemplate中定义了对5种数据结构操作:
redisTemplate.opsForValue() :操作字符串
redisTemplate.opsForHash() :操作hash
redisTemplate.opsForList() :操作list
redisTemplate.opsForSet() :操作set
redisTemplate.opsForZSet() :操作有序set
创建RedisService类
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service; /**
* redisTemple 的Service类
*/
@Service
public class RedisService {
@Autowired
private RedisTemplate<String,Object> redisTemplate; public void setObj(String key,User value) {
redisTemplate.opsForValue().set(key,value);
} public User getObj(String key) {
return (User)redisTemplate.opsForValue().get(key);
}
}
测试类
@RunWith(SpringRunner.class)
@SpringBootTest
public class RedisServiceTest { @Autowired
private RedisService redisService; @Test
public void setObj() {
redisService.setObj("user",new User("小明",22));
User user = redisService.getObj("user");
System.out.println(user.toString());
} @Test
public void getObj() {
User user = redisService.getObj("user");
System.out.println(user.toString());
}
}
至此,基础配置已完成。redis还可以解决很多关系型数据库所不能解决的问题,可以实现缓存,可以实现持久化、可以做分布式锁等等。
SpringBoot2.x集成Redis (StringTemplate与redisTemplate的用法)的更多相关文章
- Springboot2.x集成Redis集群模式
Springboot2.x集成Redis集群模式 说明 Redis集群模式是Redis高可用方案的一种实现方式,通过集群模式可以实现Redis数据多处存储,以及自动的故障转移.如果想了解更多集群模式的 ...
- Springboot2.x集成Redis哨兵模式
Springboot2.x集成Redis哨兵模式 说明 Redis哨兵模式是Redis高可用方案的一种实现方式,通过哨兵来自动实现故障转移,从而保证高可用. 准备条件 pom.xml中引入相关jar ...
- springboot2.X 集成redis+消息发布订阅
需求场景:分布式项目中,每个子项目有各自的 user 数据库, 在综合管理系统中存放这所有用户信息, 为了保持综合管理系统用户的完整性, 子系统添加用户后将用户信息以json格式保存至redis,然后 ...
- Springboot2.x 集成redis
pom.xml 添加 <dependency> <groupId>org.springframework.boot</groupId> <artifactId ...
- SpringBoot2.0 基础案例(08):集成Redis数据库,实现缓存管理
一.Redis简介 Spring Boot中除了对常用的关系型数据库提供了优秀的自动化支持之外,对于很多NoSQL数据库一样提供了自动化配置的支持,包括:Redis, MongoDB, Elastic ...
- Springboot2.x集成单节点Redis
Springboot2.x集成单节点Redis 说明 在Springboot 1.x版本中,默认使用Jedis客户端来操作Redis,而在Springboot 2.x 版本中,默认使用Lettuce客 ...
- Springboot2.x+shiro+redis(Lettuce)整合填坑
主要记录关键和有坑的地方 前提: 1.SpringBoot+shiro已经集成完毕,如果没有集成,先查阅之前的Springboot2.0 集成shiro权限管理 2.redis已经安装完成 3.red ...
- SpringBoot- springboot集成Redis出现报错:No qualifying bean of type 'org.springframework.data.redis.connection.RedisConnectionFactory'
Springboot将accessToke写入Redisk 缓存,springboot集成Redis出现报错 No qualifying bean of type 'org.springframewo ...
- Springboot2.x使用redis作为缓存
一.Springboot2.x关于配置redis作为缓存. 基本配置如下: (1)在application.properties文件中 spring.redis.database=2 //第几个数据库 ...
随机推荐
- 空间金字塔池化 ssp-net
<Spatial Pyramid Pooling in Deep Convolutional Networks for Visual Recognition>,这篇paper提出了空间金字 ...
- MnasNet:经典轻量级神经网络搜索方法 | CVPR 2019
论文提出了移动端的神经网络架构搜索方法,该方法主要有两个思路,首先使用多目标优化方法将模型在实际设备上的耗时融入搜索中,然后使用分解的层次搜索空间,来让网络保持层多样性的同时,搜索空间依然很简洁,能够 ...
- 动手实现 LRU 算法,以及 Caffeine 和 Redis 中的缓存淘汰策略
我是风筝,公众号「古时的风筝」. 文章会收录在 JavaNewBee 中,更有 Java 后端知识图谱,从小白到大牛要走的路都在里面. 那天我在 LeetCode 上刷到一道 LRU 缓存机制的问题, ...
- Python3 迭代器深入解析
第6章 函数 6.1 函数的定义和调用 6.2 参数传递 6.3 函数返回值 6.4 变量作用域 6.5 匿名函数(lambda) 6.6 递归函数 6.7 迭代器 6.8 生成器 6.9 装饰器 6 ...
- Python Hacking Tools - Port Scanner
Socket Programming 1. Scan the target Vulnerable Server. And test it by telnet. 2. Write the scanne ...
- CSS变形动画
CSS变形动画 前言 在开始介绍CSS变形动画之前,可以先了解一下学习了它之后能做什么,有什么用,这样你看这篇文章可能会有一些动力. 学习了CSS变形动画后,你可以为你的页面做出很多炫酷的效果,如一个 ...
- Html笔试复习
掌握学习技巧,提高学习质量 学习目标:熟练掌握Html笔试复习题 已掌握目标:Html笔试复习题掌握95% 未完成目标:个别题因粗心造成错误,因选项意思不懂出错 解决方案:了解原因,因错出方案,充分利 ...
- WEB前端常见受攻击方式及解决办法
一个网站建立以后,如果不注意安全方面的问题,很容易被人攻击,下面就讨论一下几种漏洞情况和防止攻击的办法. 一.SQL注入 所谓SQL注入,就是通过把SQL命令插入到Web表单提交或输入域名或页面请求的 ...
- 性能测试 -- docker安装influxdb
一.前提 1.项目已经部署好 2.docker已经安装好 二.docker安装influxdb 1.下载influxdb镜像:docker pull tutum/influxdb 1)超时报错: ...
- 重学c#系列——c# 托管和非托管资源与代码相关(四)
前言 这是续第三节. 概况垃圾回收与我们写代码的关系: 强引用和弱引用 针对共享 Web 承载优化 垃圾回收和性能 应用程序域资源监视 正文 强引用和弱引用 垃圾回收器不能回收仍在引用的对象的内存-- ...