SpringBoot2.0 基础案例(08):集成Redis数据库,实现缓存管理
一、Redis简介
Spring Boot中除了对常用的关系型数据库提供了优秀的自动化支持之外,对于很多NoSQL数据库一样提供了自动化配置的支持,包括:Redis, MongoDB, Elasticsearch。这些案例整理好后,陆续都会上传Git。
SpringBoot2 版本,支持的组件越来越丰富,对Redis的支持不仅仅是扩展了API,更是替换掉底层Jedis的依赖,换成Lettuce。
本案例需要本地安装一台Redis数据库。
二、Spring2.0集成Redis
1、核心依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2、配置文件
# 端口
server:
port: 8008
spring:
application:
# 应用名称
name: node08-boot-redis
# redis 配置
redis:
host: 127.0.0.1
#超时连接
timeout: 1000ms
jedis:
pool:
#最大连接数据库连接数,设 0 为没有限制
max-active: 8
#最大等待连接中的数量,设 0 为没有限制
max-idle: 8
#最大建立连接等待时间。如果超过此时间将接到异常。设为-1表示无限制。
max-wait: -1ms
#最小等待连接中的数量,设 0 为没有限制
min-idle: 0
这样Redis的环境就配置成功了,已经可以直接使用封装好的API了。
3、简单测试案例
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;
@RestController
public class RedisController {
@Resource
private StringRedisTemplate stringRedisTemplate ;
@RequestMapping("/setGet")
public String setGet (){
stringRedisTemplate.opsForValue().set("cicada","smile");
return stringRedisTemplate.opsForValue().get("cicada") ;
}
@Resource
private RedisTemplate redisTemplate ;
/**
* 设置 Key 的有效期 10 秒
*/
@RequestMapping("/setKeyTime")
public String setKeyTime (){
redisTemplate.opsForValue().set("timeKey","timeValue",10, TimeUnit.SECONDS);
return "success" ;
}
@RequestMapping("/getTimeKey")
public String getTimeKey (){
// 这里 Key 过期后,返回的是字符串 'null'
return String.valueOf(redisTemplate.opsForValue().get("timeKey")) ;
}
}
4、自定义序列化配置
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.io.Serializable;
/**
* Redis 配置
*/
@Configuration
public class RedisConfig {
private static final Logger LOGGER = LoggerFactory.getLogger(RedisConfig.class) ;
/**
* 序列化配置
*/
@Bean
public RedisTemplate<String, Serializable> redisTemplate
(LettuceConnectionFactory redisConnectionFactory) {
LOGGER.info("RedisConfig == >> redisTemplate ");
RedisTemplate<String, Serializable> template = new RedisTemplate<>();
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
template.setConnectionFactory(redisConnectionFactory);
return template;
}
}
5、序列化测试
import com.boot.redis.entity.User;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
@RestController
public class SerializeController {
@Resource
private RedisTemplate redisTemplate ;
@RequestMapping("/setUser")
public String setUser (){
User user = new User() ;
user.setName("cicada");
user.setAge(22);
List<String> list = new ArrayList<>() ;
list.add("小学");
list.add("初中");
list.add("高中");
list.add("大学");
user.setEducation(list);
redisTemplate.opsForValue().set("userInfo",user);
return "success" ;
}
@RequestMapping("/getUser")
public User getUser (){
return (User)redisTemplate.opsForValue().get("userInfo") ;
}
}
三、源代码地址
GitHub地址:知了一笑
https://github.com/cicadasmile
码云地址:知了一笑
https://gitee.com/cicadasmile

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。
持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。
转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。
-
上一篇
JAVA8 MAP新增方法详解
1、compute default V compute(K key,BiFunction<? super K,? super V,? extends V> remappingFunction)Attempts to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping). 尝试通过Lambda表达式重新计算给定KEY的映射值并更新MAP(值为null则删除KEY,否则重新写入)。 Map<String, String> tMap = new HashMap<String, String>() { { put("A", "AAA"); put("B", "BBB"); } }; tMap.compute("A", (k, v) -> v == null ? "AAA" : v.concat("AAA"));//KEY存在VALUE不为空且Lambda计算结果不为空,更新KEY Syst...
-
下一篇
基于Tensorflow的人工智能算法入门
coding=utf-8 引用数据分析模块 import numpy as np 引用文档读取模块,可以读取csv、json等文件 import pandas as pd 引用人工智能算法模块,里面包含相关算法 import tensorflow as tf 引用数据人工智能分析模块,并引用数据拆分功能 from sklearn.model_selection import train_test_split 初始化数据 从文件读取数据 data = pd.read_csv('data/XXX.csv') 为空值的列补充0值 data = data.fillna(0) 转换XX为1,XXX为2 data['XXX'] = data['XXX'].apply(lambda s: 1 if s == 'XXX' else 0) 添加新列Deceased 值为Survived 取非 独立热编码,就是使用N位布尔型的状态标识来对N种状态进行编码,任意时刻编码中只有一位有效(one-hot编码) data['XXX'] = data['XXX'].apply(lambda s: 1 - s) 选取...
相关文章
文章评论
共有0条评论来说两句吧...
文章二维码
点击排行
推荐阅读
最新文章
- Docker快速安装Oracle11G,搭建oracle11g学习环境
- Red5直播服务器,属于Java语言的直播服务器
- SpringBoot2全家桶,快速入门学习开发网站教程
- SpringBoot2配置默认Tomcat设置,开启更多高级功能
- SpringBoot2更换Tomcat为Jetty,小型站点的福音
- CentOS8编译安装MySQL8.0.19
- MySQL数据库在高并发下的优化方案
- SpringBoot2编写第一个Controller,响应你的http请求并返回结果
- Springboot2将连接池hikari替换为druid,体验最强大的数据库连接池
- SpringBoot2初体验,简单认识spring boot2并且搭建基础工程