SpringBoot中Redis的基础使用
基础使用
首先引入依赖
<!-- redis依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
然后在application.yml的spring下增加redis配置:

代码如下
redis:
# Redis数据库索引(默认为0)
database: 0
# Redis服务器地址
host: 127.0.0.1
# Redis服务器连接端口
port: 6379
password: '123456'
jedis:
pool:
# 连接池最大连接数(使用负值表示没有限制)
max-active: 8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
max-wait: 1
# 连接池中的最大空闲连接
max-idle: 8
# 连接池中的最小空闲连接
min-idle: 0
# 连接超时时间(毫秒)
timeout: 5000
然后在根包下创建一个service的文件夹加,然后在里面增加redis文件夹,redis文件夹里编写redis的基础操作函数。
编写IRedisService接口,编写增删改查函数,代码如下:
import java.util.Map;
@Service
public interface IRedisService {
/**
* 加入元素
* @param key
* @param value
*/
void setValue(String key, Map<String, Object> value);
/**
* 加入元素
* @param key
* @param value
*/
void setValue(String key, String value);
/**
* 加入元素
* @param key
* @param value
*/
void setValue(String key, Object value);
/**
* 获取元素
* @param key
*/
Object getMapValue(String key);
/**
* 获取元素
* @param key
*/
Object getValue(String key);
}
编写RedisServiceImpl实现,实现Redis的增删改查。
package com.example.dynamicdb.service.redis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import java.util.Map;
import java.util.concurrent.TimeUnit;
@Service("RedisServiceImpl")
public class RedisServiceImpl implements IRedisService {
public RedisServiceImpl(){}
@Autowired
private RedisTemplate redisTemplate;
@Override
public void setValue(String key, Map<String, Object> value) {
ValueOperations<String, Object> vo = redisTemplate.opsForValue();
vo.set(key, value);
redisTemplate.expire(key, 1, TimeUnit.HOURS);
}
@Override
public Object getValue(String key) {
ValueOperations<String, String> vo = redisTemplate.opsForValue();
return vo.get(key);
}
@Override
public void setValue(String key, String value) {
ValueOperations<String, Object> vo = redisTemplate.opsForValue();
vo.set(key, value);
redisTemplate.expire(key, 1, TimeUnit.HOURS);
}
@Override
public void setValue(String key, Object value) {
ValueOperations<String, Object> vo = redisTemplate.opsForValue();
vo.set(key, value);
redisTemplate.expire(key, 1, TimeUnit.HOURS);
}
@Override
public Object getMapValue(String key) {
ValueOperations<String, String> vo = redisTemplate.opsForValue();
return vo.get(key);
}
}
然后创建一个RedisController,编写一个测试接口,如下:
@RestController
public class RedisController {
@Resource(name = "RedisServiceImpl")//使用resource实例化对象,name是指定实例化的类,用于一个接口多个类继承的情况
private IRedisService iRedisService;
@PostMapping(value = "/Redis/TestRedis")
@ApiOperation(value = "redis测试接口", notes = "redis测试接口", httpMethod = "POST")
public String TestRedis(){
iRedisService.setValue("redis", "这是redis的测试数据");
Object redis = iRedisService.getValue("redis");
return redis.toString();
}
}
redis缓存使用
首先创建一个config文件夹,然后创建一个RedisCacheConfig文件,代码如下:
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
@EnableCaching
@Configuration
public class RedisCacheConfig {
/**
* 最新版,设置redis缓存过期时间
*/
@Bean
public RedisCacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
return new RedisCacheManager(
RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory),
this.getRedisCacheConfigurationWithTtl( 60), // 默认策略,未配置的 key 会使用这个
this.getRedisCacheConfigurationMap() // 指定 key 策略
);
}
private Map<String, RedisCacheConfiguration> getRedisCacheConfigurationMap() {
Map<String, RedisCacheConfiguration> redisCacheConfigurationMap = new HashMap<>();
//SsoCache和BasicDataCache进行过期时间配置
redisCacheConfigurationMap.put("messagCache", this.getRedisCacheConfigurationWithTtl(30 * 60));
//自定义设置缓存时间
redisCacheConfigurationMap.put("studentCache", this.getRedisCacheConfigurationWithTtl(60 ));
return redisCacheConfigurationMap;
}
private RedisCacheConfiguration getRedisCacheConfigurationWithTtl(Integer seconds) {
Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();
redisCacheConfiguration = redisCacheConfiguration.serializeValuesWith(
RedisSerializationContext
.SerializationPair
.fromSerializer(jackson2JsonRedisSerializer)
).entryTtl(Duration.ofSeconds(seconds));
return redisCacheConfiguration;
}
}
类名上有注解@Configuration,代表该类会在启动时加入进bean集合。
然后在RedisController下编写测试函数,如下:
@Autowired
private SqlSession sqlSession;
@GetMapping(value = "/Redis/TestRedisCache")
@ResponseBody
@DS("db2")
@Cacheable(cacheNames = "userCache", key = "#id")
@ApiOperation(value="查询单条记录",notes = "查询")
public List<user> TestRedisCache(Integer id) {
//读取第二个数据库的值
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<user> users = mapper.test();
return users;
}
使用@Cacheable注解缓存接口的返回值,cacheNames的值和key的值,组合起来成为是缓存中的键值对的key值,如下图。

----------------------------------------------------------------------------------------------------
到此,SpringBoot中Redis的基础使用就已经介绍完了。
代码已经传到Github上了,欢迎大家下载。
Github地址:https://github.com/kiba518/dynamicdb
----------------------------------------------------------------------------------------------------
注:此文章为原创,任何形式的转载都请联系作者获得授权并注明出处!
若您觉得这篇文章还不错,请点击下方的【推荐】,非常感谢!
https://www.cnblogs.com/kiba/p/17480377.html

SpringBoot中Redis的基础使用的更多相关文章
- SpringBoot中Redis的set、map、list、value、实体类等基本操作介绍
今天给大家介绍一下SpringBoot中Redis的set.map.list.value等基本操作的具体使用方法 上一节中给大家介绍了如何在SpringBoot中搭建Redis缓存数据库,这一节就针对 ...
- springboot中redis取缓存类型转换异常
异常如下: [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested ...
- SpringBoot中redis的使用介绍
REmote DIctionary Server(Redis) 是一个由Salvatore Sanfilippo写的key-value存储系统. Redis是一个开源的使用ANSI C语言编写.遵守B ...
- ③SpringBoot中Redis的使用
本文基于前面的springBoot系列文章进行学习,主要介绍redis的使用. SpringBoot对常用的数据库支持外,对NoSQL 数据库也进行了封装自动化. redis介绍 Redis是目前业界 ...
- SpringBoot中Redis的使用
转载:http://www.ityouknow.com/springboot/2016/03/06/spring-boot-redis.html Spring Boot 对常用的数据库支持外,对 No ...
- springboot中redis的缓存穿透问题
什么是缓存穿透问题?? 我们使用redis是为了减少数据库的压力,让尽量多的请求去承压能力比较大的redis,而不是数据库.但是高并发条件下,可能会在redis还没有缓存的时候,大量的请求同时进入,导 ...
- springBoot 中redis 注解缓存的使用
1,首先在启动类上加上 @EnableCaching 这个注解 在查询类的controller,或service ,dao 中方法上加 @Cacheable 更新或修改方法上加 @CachePut 注 ...
- springboot中redis做缓存时的配置
import com.google.common.collect.ImmutableMap;import org.slf4j.Logger;import org.slf4j.LoggerFactory ...
- springboot中Redis的Lettuce客户端和jedis客户端
1.引入客户端依赖 <!--jedis客户端依赖--> <dependency> <groupId>redis.clients</groupId> &l ...
- springboot中redis使用和工具
application.properties #Redis相关配置 spring.data.redis.host=localhost #端口 spring.data.redis.port=6379 # ...
随机推荐
- [转帖]在麒麟Linux安装Postgis
https://jimolonely.github.io/tech/linux/install-postgis-kylin/ 接着上一篇在麒麟linux上安装Postgresql12.5 ,我们来安装 ...
- [转帖]xargs详解
https://www.cnblogs.com/xiaofeng666/p/10800939.html xargs与find经常结合来进行文件操作,平时删日志的时候只是习惯的去删除,比如 # find ...
- Bitmap、RoaringBitmap原理分析
作者:京东科技 曹留界 在人群本地化实践中我们介绍了人群ID中所有的pin的偏移量可以通过Bitmap存储,而Bitmap所占用的空间大小只与偏移量的最大值有关系.假如现在要向Bitmap内存入两个p ...
- 【笔记】macbook m2 芯片中使用 gcc docker 镜像来交叉编译
作者:张富春(ahfuzhang),转载时请注明作者和引用链接,谢谢! cnblogs博客 zhihu Github 公众号:一本正经的瞎扯 一个 c 程序,如何在 macbook m2 芯片的笔记本 ...
- 【解决了一个小问题】vm-agent中,如何对envoy这样的特殊expoter路径做处理?
作者:张富春(ahfuzhang),转载时请注明作者和引用链接,谢谢! cnblogs博客 zhihu Github 公众号:一本正经的瞎扯 envoy这个组件的expoter路径为 /stats/p ...
- 【JS 逆向百例】webpack 改写实战,G 某游戏 RSA 加密
关注微信公众号:K哥爬虫,QQ交流群:808574309,持续分享爬虫进阶.JS/安卓逆向等技术干货! 声明 本文章中所有内容仅供学习交流,抓包内容.敏感网址.数据接口均已做脱敏处理,严禁用于商业用途 ...
- TienChin 渠道管理-渠道类型
在上一篇文章当中,表里面有一个渠道类型,我们这节主要是将这个渠道类型创建好,首先我们来看看字典表. sys_dict_type 表: 字段名 数据类型 注释 dict_id bigint 字典主键 d ...
- 知识蒸馏相关技术【模型蒸馏、数据蒸馏】以ERNIE-Tiny为例
1.任务简介 基于ERNIE预训练模型效果上达到业界领先,但是由于模型比较大,预测性能可能无法满足上线需求. 直接使用ERNIE-Tiny系列轻量模型fine-tune,效果可能不够理想.如果采用数据 ...
- 强化学习从基础到进阶-常见问题和面试必知必答[6]:演员-评论员算法(advantage actor-critic,A2C),异步A2C、与生成对抗网络的联系等详解
强化学习从基础到进阶-常见问题和面试必知必答[6]:演员-评论员算法(advantage actor-critic,A2C),异步A2C.与生成对抗网络的联系等详解 1.核心词汇 优势演员-评论员(a ...
- Flask 框架:实现简单API测试接口
通过使用Python中Flask框架实现一个简单的API接口程序,用户可发送JSON格式的请求,服务器响应请求,并以JSON格式将数据返回给用户,此处代码是一个模板可以测试接口时使用. Flask代码 ...