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 //第几个数据库 ...
随机推荐
- Thymeleaf模板引擎学习
开发传统Java WEB项目时,我们可以使用JSP页面模板语言,但是在SpringBoot中已经不推荐使用JSP页面进行页面渲染了.从而Thymeleaf提供了一个用于整合Spring MVC的可选模 ...
- three.js 曲线
上几篇说了three.js的曲线,这篇来郭先生来说说three.js曲线,在线案例点击郭先生的博客查看. 1. 了解three.js曲线 之前已经说了一些three.js的几何体,这篇说一说three ...
- Linux-常见的命令
1.杀掉tomcat进程 ps -ef |grep tomcat kill -9 pid 2.启动http服务 service httpd start 3.停止mysql服务 servi ...
- 手写简易的Mybatis
手写简易的Mybatis 此篇文章用来记录今天花个五个小时写出来的简易版mybatis,主要实现了基于注解方式的增删查改,目前支持List,Object类型的查找,参数都是基于Map集合的,可以先看一 ...
- React js ReactDOM.render 语句后面不能加分号
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title&g ...
- toad for oracle 小技巧
在SQL*LOADER 工具上(或者称为SQLLDR,读为:“sequel loader”),因为它仍然是装载数据的主要方法,SQLLDR 能够在极短的时间内装 载庞大数量的数据. 我也是初使用,理解 ...
- 肝了两天IntelliJ IDEA 2020,解锁11种新姿势, 真香!!!
IDEA2020版本正式发布已经有3个月了,当时由于各方面原因(太懒)也没有去尝试新功能.于是这个周末特意去在另一个电脑上下载了最新版的IDEA,并尝试了一下.总的来说呢,体验上明显的提升. 作为一个 ...
- MySQL数据库的安装方法
- 浅谈Python中的深浅拷贝的区别
深.浅拷贝总结 深拷贝 拷贝可变数据类型,如列表容器: a = [1, 2, [3, 4]] b = copy.deepcopy(a) a 与 b 所指的列表容器的空间地址不一致,即 id(a) != ...
- 题解 洛谷 P3734 【[HAOI2017]方案数】
可以先考虑没有障碍物的情况,设计状态\(f_{i,j,k}\),表示到达坐标 \((x,y,z)\)二进制下,\(x\)有\(i\)位,\(y\)有\(j\)位,\(z\)有\(k\)位的方案数. 得 ...