Spring Boot整合Spring Cache及Redis过程解析
这篇文章主要介绍了SpringBoot整合SpringCache及Redis过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
1.安装redis
a.由于官方是没有Windows版的,所以我们需要下载微软开发的redis,网址:
https://github.com/MicrosoftArchive/redis/releases
b.解压后,在redis根目录打开cmd界面,输入:redis-server.exeredis.windows.conf,启动redis(关闭cmd窗口即停止)
2.使用
a.创建SpringBoot工程,选择maven依赖
org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-thymeleaf ..... org.springframework.boot spring-boot-starter-data-redis
b.配置application.yml配置文件
server: port:8080 spring: #redis相关配置 redis: database:0 host:localhost port:6379 password: jedis: pool: #连接池最大连接数(使用负值表示没有限制) max-active:8 #连接池最大阻塞等待时间(使用负值表示没有限制) max-wait:-1ms #连接池中的最大空闲连接 max-idle:5 #连接池中的最小空闲连接 min-idle:0 #连接超时时间(毫秒)默认是2000ms timeout:2000ms #thymeleaf热更新 thymeleaf: cache:false
c.创建RedisConfig配置类
@Configuration @EnableCaching//开启缓存 publicclassRedisConfig{ /** *缓存管理器 *@paramredisConnectionFactory *@return */ @Bean publicRedisCacheManagercacheManager(RedisConnectionFactoryredisConnectionFactory){ //生成一个默认配置,通过config对象即可对缓存进行自定义配置 RedisCacheConfigurationconfig=RedisCacheConfiguration.defaultCacheConfig(); //设置缓存的默认过期时间,也是使用Duration设置 config=config.entryTtl(Duration.ofMinutes(30)) //设置key为string序列化 .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(newStringRedisSerializer())) //设置value为json序列化 .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer())) //不缓存空值 .disableCachingNullValues(); //对每个缓存空间应用不同的配置 MapconfigMap=newHashMap<>(); configMap.put("userCache",config.entryTtl(Duration.ofSeconds(60))); //使用自定义的缓存配置初始化一个cacheManager RedisCacheManagercacheManager=RedisCacheManager.builder(redisConnectionFactory) //默认配置 .cacheDefaults(config) //特殊配置(一定要先调用该方法设置初始化的缓存名,再初始化相关的配置) .initialCacheNames(configMap.keySet()) .withInitialCacheConfigurations(configMap) .build(); returncacheManager; } /** *Redis模板类redisTemplate *@paramfactory *@return */ @Bean publicRedisTemplateredisTemplate(RedisConnectionFactoryfactory){ RedisTemplate template=newRedisTemplate<>(); template.setConnectionFactory(factory); //key采用String的序列化方式 template.setKeySerializer(newStringRedisSerializer()); //hash的key也采用String的序列化方式 template.setHashKeySerializer(newStringRedisSerializer()); //value序列化方式采用jackson template.setValueSerializer(jackson2JsonRedisSerializer()); //hash的value序列化方式采用jackson template.setHashValueSerializer(jackson2JsonRedisSerializer()); returntemplate; } /** *json序列化 *@return */ privateRedisSerializer
d.创建entity实体类
publicclassUserimplementsSerializable{ privateintid; privateStringuserName; privateStringuserPwd; publicUser(){} publicUser(intid,StringuserName,StringuserPwd){ this.id=id; this.userName=userName; this.userPwd=userPwd; } publicintgetId(){ returnid; } publicvoidsetId(intid){ this.id=id; } publicStringgetUserName(){ returnuserName; } publicvoidsetUserName(StringuserName){ this.userName=userName; } publicStringgetUserPwd(){ returnuserPwd; } publicvoidsetUserPwd(StringuserPwd){ this.userPwd=userPwd; } }
e.创建Service
@Service publicclassUserService{ //查询:先查缓存是是否有,有则直接取缓存中数据,没有则运行方法中的代码并缓存 @Cacheable(value="userCache",key="'user:'+#userId") publicUsergetUser(intuserId){ System.out.println("执行此方法,说明没有缓存"); returnnewUser(userId,"用户名(get)_"+userId,"密码_"+userId); } //添加:运行方法中的代码并缓存 @CachePut(value="userCache",key="'user:'+#user.id") publicUseraddUser(Useruser){ intuserId=user.getId(); System.out.println("添加缓存"); returnnewUser(userId,"用户名(add)_"+userId,"密码_"+userId); } //删除:删除缓存 @CacheEvict(value="userCache",key="'user:'+#userId") publicbooleandeleteUser(intuserId){ System.out.println("删除缓存"); returntrue; } @Cacheable(value="common",key="'common:user:'+#userId") publicUsergetCommonUser(intuserId){ System.out.println("执行此方法,说明没有缓存(测试公共配置是否生效)"); returnnewUser(userId,"用户名(common)_"+userId,"密码_"+userId); } }
f.创建Controller
@RestController @RequestMapping("/user") publicclassUserController{ @Resource privateUserServiceuserService; @RequestMapping("/getUser") publicUsergetUser(intuserId){ returnuserService.getUser(userId); } @RequestMapping("/addUser") publicUseraddUser(Useruser){ returnuserService.addUser(user); } @RequestMapping("/deleteUser") publicbooleandeleteUser(intuserId){ returnuserService.deleteUser(userId); } @RequestMapping("/getCommonUser") publicUsergetCommonUser(intuserId){ returnuserService.getCommonUser(userId); } }
@Controller publicclassHomeController{ //默认页面 @RequestMapping("/") publicStringlogin(){ return"test"; } }
g.在templates目录下,写书test.html页面
test .row{ margin:10px0px; } .col{ display:inline-block; margin:0px5px; } 测试
获取用户