整合Cache+Redis

参考链接:https://www.cnblogs.com/wenjunwei/p/10779450.html
http://www.ityouknow.com/springboot/2016/03/06/spring-boot-redis.html

一、说明:

1、Cache的作用:cache配置在方法上,如果对应缓存中已经有数据,则方法直接返回缓存中数据;否则执行方法体,并把返回结果加入缓存中。
2、对于缓存声明,spring的缓存提供了一组java注解:
*
@Cacheable:触发缓存写入。
*
@CacheEvict:触发缓存清除。
*
@CachePut:更新缓存(不会影响到方法的运行)。
*
@Caching:重新组合要应用于方法的多个缓存操作。
*
@CacheConfig:设置类级别上共享的一些常见缓存设置。

二:步骤:

1、添加redis依赖:

org.springframework.boot spring-boot-starter-data-redis org.apache.commons commons-pool2 2、配置redis:

#######################################################Redis
#数据库索引(默认为0)
spring.redis.database=0
#服务地址
spring.redis.host=127.0.0.1
#密码(默认为空)
spring.redis.password=
#端口
spring.redis.port=6379
#连接池最大连接数(默认为8,负数表示没有限制)
spring.redis.lettuce.pool.max-active=8
#连接池最大阻塞等待时间(默认为-1,负数表示没有限制)
spring.redis.lettuce.pool.max-wait=-1
#连接池最大空闲连接数(默认为8)
spring.redis.lettuce.pool.max-idle=8
#连接池最小空闲连接数(默认为0)
spring.redis.lettuce.pool.min-idle=0
3、创建配置类,主要是使用@EnableCaching开启缓存。当然了,该注解也可以加载启动类上。

import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
}
4、创建controller类,测试缓存:

package com.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.text.SimpleDateFormat;
import java.util.Date;

@RestController
public class RedisController {

/**
  * user-key:为缓存名称,一个缓存中可以有多个键值对。不能为空,可以指定多个,如{"cache1","cache2"}
  * key:为缓存中的键。可以为空,如果为空,则使用自带的key生成工具。该方法中使用入参作为key
  * @param id
  * @return
*/
@RequestMapping("cache")
@Cacheable(value = "user-key",key = "#id")
public String cache(String id) {
    SimpleDateFormat sdf = new SimpleDateFormat("YYYY-mm-dd HH:mm:ss");
    System.out.println("----------------增加缓存");
    return sdf.format(new Date());
}

}
5、结果:
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值