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的用法)的更多相关文章

  1. Springboot2.x集成Redis集群模式

    Springboot2.x集成Redis集群模式 说明 Redis集群模式是Redis高可用方案的一种实现方式,通过集群模式可以实现Redis数据多处存储,以及自动的故障转移.如果想了解更多集群模式的 ...

  2. Springboot2.x集成Redis哨兵模式

    Springboot2.x集成Redis哨兵模式 说明 Redis哨兵模式是Redis高可用方案的一种实现方式,通过哨兵来自动实现故障转移,从而保证高可用. 准备条件 pom.xml中引入相关jar ...

  3. springboot2.X 集成redis+消息发布订阅

    需求场景:分布式项目中,每个子项目有各自的 user 数据库, 在综合管理系统中存放这所有用户信息, 为了保持综合管理系统用户的完整性, 子系统添加用户后将用户信息以json格式保存至redis,然后 ...

  4. Springboot2.x 集成redis

    pom.xml 添加 <dependency> <groupId>org.springframework.boot</groupId> <artifactId ...

  5. SpringBoot2.0 基础案例(08):集成Redis数据库,实现缓存管理

    一.Redis简介 Spring Boot中除了对常用的关系型数据库提供了优秀的自动化支持之外,对于很多NoSQL数据库一样提供了自动化配置的支持,包括:Redis, MongoDB, Elastic ...

  6. Springboot2.x集成单节点Redis

    Springboot2.x集成单节点Redis 说明 在Springboot 1.x版本中,默认使用Jedis客户端来操作Redis,而在Springboot 2.x 版本中,默认使用Lettuce客 ...

  7. Springboot2.x+shiro+redis(Lettuce)整合填坑

    主要记录关键和有坑的地方 前提: 1.SpringBoot+shiro已经集成完毕,如果没有集成,先查阅之前的Springboot2.0 集成shiro权限管理 2.redis已经安装完成 3.red ...

  8. 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 ...

  9. Springboot2.x使用redis作为缓存

    一.Springboot2.x关于配置redis作为缓存. 基本配置如下: (1)在application.properties文件中 spring.redis.database=2 //第几个数据库 ...

随机推荐

  1. JavaScript之setinterval的具体使用

    关于setInterval在api文档中也有很详细的解释,比如下面那两个: setInterval() 方法可按照指定的周期(以毫秒计)来调用函数或计算表达式. setInterval() 方法会不停 ...

  2. How to use the function of bind

    The usage of  bind  is to define a specified scope for called function. Because the key this is easy ...

  3. Quartz.Net系列(十二):六大Calendar(Annual、Cron、Daily、Holiday、Monthly、Weekly)

    Quartz.Net中为了动态排除一些时间,而使用Calendar可以做到 1.DailyCalendar 可以动态的排除一天中的某些时间段 示例:在一天当中的13:00到14:00不要执行 publ ...

  4. Python 实现邮件发送功能(初级)

    在我们日常项目中,会经常使用到邮件的发送功能,如何利用Python发送邮件也是一项必备的技能.本文主要讲述利用Python来发送邮件的一些基本操作. 本章主要包含知识点: 邮件发送原理简述即常用smt ...

  5. bzoj3673可持久化并查集 by zky&&bzoj3674可持久化并查集加强版

    bzoj3673可持久化并查集 by zky 题意: 维护可以恢复到第k次操作后的并查集. 题解: 用可持久化线段树维护并查集的fa数组和秩(在并查集里的深度),不能路径压缩所以用按秩启发式合并,可以 ...

  6. 采用 Unicode 标点属性方式的正则表达式,可以去掉所有的标点符号,

    public class Test { public static void main(String[] args) { String str = "!!!??!!!!%*)%¥!KTV去符 ...

  7. GitHub 热点速览 Vol.29:程序员资料大全

    作者:HelloGitHub-小鱼干 摘要:有什么资料比各种大全更吸引人的呢?先马为敬,即便日后"挺尸"收藏夹,但是每个和程序相关的大全项目都值得一看.比如国内名为小傅哥整理的 J ...

  8. MySQL的权限赋予

    MySQL 赋予用户权限命令的简单格式可概括为:grant 权限 on 数据库对象 to 用户 一.grant 普通数据用户,查询.插入.更新.删除 数据库中所有表数据的权利. grant selec ...

  9. JDBC 连接 MySQL 8.0.15+ 常见错误记录

    课后复习 1. No suitable driver found for mysql:jdbc://localhost:3306/test 错误原因: mysql:jdbc://localhost:3 ...

  10. spring学习(三)属性注入

    用的是IDEA的maven工程,pom.xml文件导包依赖省略 本文主要写set方式注入 (一).一般类型注入 一.写两个实体类Car.User public class Car { private ...