博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
springboot -- Redis初了解与使用
阅读量:3921 次
发布时间:2019-05-23

本文共 3930 字,大约阅读时间需要 13 分钟。

前言:

据我目前的了解, Redis就是一个管理缓存的工具, 对缓存进行操作

1、启用Redis服务

在这里插入图片描述

切换路径: cd /d F:\Redis
开启Redis: redis-server.exe redis.windows.conf

1、导入相关依赖

org.springframework.boot
spring-boot-starter-data-redis

这里我把版本注释掉, 让springboot自动适配版本, 否则会报错。

2、application.yml配置

spring:  redis:    host: localhost    port: 6379

配置好端口号和IP地址

3、储存数据时序列化的配置

package com.example.config;import org.springframework.context.annotation.Configuration;import java.net.UnknownHostException;import java.time.Duration;import org.springframework.beans.factory.annotation.Qualifier;import org.springframework.cache.CacheManager;import org.springframework.cache.annotation.CachingConfigurerSupport;import org.springframework.context.annotation.Bean;import org.springframework.data.redis.cache.RedisCacheConfiguration;import org.springframework.data.redis.cache.RedisCacheManager;import org.springframework.data.redis.connection.RedisConnectionFactory;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;import org.springframework.data.redis.serializer.RedisSerializationContext;import org.springframework.data.redis.serializer.RedisSerializer;import org.springframework.data.redis.serializer.StringRedisSerializer;import com.fasterxml.jackson.annotation.PropertyAccessor;import com.fasterxml.jackson.databind.ObjectMapper;@Configurationpublic class MyRedisConfg extends CachingConfigurerSupport {		/**	 * 配置redisCacheManager存放缓存的格式	 * @param factory	 * @return	 */	@Bean("redisCacheManager")	public RedisCacheManager redisCacheManager(RedisConnectionFactory factory){		System.out.println("加载Redis..");		RedisCacheConfiguration cacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()		.entryTtl(Duration.ofDays(1))		.disableCachingNullValues()		.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));		return RedisCacheManager.builder(factory).cacheDefaults(cacheConfiguration).build();	}			/**	 * 配置RedisTemplate存放缓存的格式	 * @param factory	 * @return	 */	@Bean    public RedisTemplate
redisTemplate( RedisConnectionFactory redisConnectionFactory) throws UnknownHostException { RedisTemplate
template = new RedisTemplate
(); template.setConnectionFactory(redisConnectionFactory); Jackson2JsonRedisSerializer
ser = new Jackson2JsonRedisSerializer(Object.class); template.setDefaultSerializer(ser); return template; }}

这样的话, 储存到Redis数据库中的对象就以json格式来呈现了。

4、使用编码方式添加缓存(当然 RedisCacheManager和RedisTemplate功能是没什么区别的,RedisCacheManager可能包含着RedisTemplate)

@Autowired    RedisCacheManager deptCacheManager;	 public Department getDeptById(Integer id){        System.out.println("查询部门"+id);        Department department = departmentMapper.getDeptById(id);        //获取某个缓存        Cache dept = deptCacheManager.getCache("dept");        dept.put("dept:1",department);        return department;    }

5、测试类

@Autowired	@Qualifier("redisCacheManager")    RedisCacheManager redisCacheManager;    	@Autowired	StringRedisTemplate stringRedisTemplate; 		@Test	public void method(){
//获取value Cache cache = redisCacheManager.getCache("category"); //添加缓存 cache.put("cc", categoryDao.getOne(1)); //很奇怪, 取不出来? //因为 redisCacheManager 取不出来缓存, 所以我用 stringRedisTemplate 去取, 取完 //需要将其转化成对象 System.out.println(stringRedisTemplate.opsForValue().get("category::cc")); }

注意:User对象在储存时要实现序列化, 否则可能会报错。

打开这个Redis软件查看保存是否成功

在这里插入图片描述

在这里插入图片描述

拓展:

@Cacheable(cacheNames = {
"emp"}, key="#id"/*, keyGenerator="cacheKey", condition = "#id>1 and #root.methodName eq 'getEmp' ", unless = "#id==2"*/) public Employee getEmp(int id){
System.out.println("查询..."); return employeeMapper.get(id); }

运行一下被缓存注解标记的方法, 得到的缓存也会储存在Redis数据库中。在这里插入图片描述

转载地址:http://yyern.baihongyu.com/

你可能感兴趣的文章
FreeSql接入CAP的实践
查看>>
浅析 EF Core 5 中的 DbContextFactory
查看>>
听说容器正在吃掉整个软件世界?
查看>>
真实经历:整整一年了,他是这样从程序员转型做产品经理的
查看>>
netcore一键部署到linux服务器以服务方式后台运行
查看>>
还在犹豫是否迁移.NET5?这几个项目已经上线了!
查看>>
被 C# 的 ThreadStatic 标记的静态变量,都存放在哪里了?
查看>>
ASP.NET Core使用HostingStartup增强启动操作
查看>>
结合控制台程序和K8S的CronJob完成定时任务
查看>>
WPF开发的实用小工具 - 快捷悬浮菜单
查看>>
.Net orm 开源项目 FreeSql 2.0.0
查看>>
IdentityServer4系列 | 简化模式
查看>>
小试YARP
查看>>
如何使用 C# 中的 HashSet
查看>>
api-hook,更轻量的接口测试工具
查看>>
一个情怀引发的生产事故(续)
查看>>
如何在 C# 中使用 RabbitMQ
查看>>
一套标准的ASP.NET Core容器化应用日志收集分析方案
查看>>
如何使用 C# 扩展方法
查看>>
C#如何回到主线程,如何在委托指定线程执行
查看>>