您的位置:首页 > 数据库 > Redis

SpringBoot缓存之redis--最简单的使用方式

2020-03-08 14:47 956 查看

第一步:配置redis

  这里使用的是yml类型的配置文件

1 mybatis:
2   mapper-locations: classpath:mapping/*.xml
3 spring:
4   datasource:
5     name: miaosha
6     url: jdbc:mysql://127.0.0.1:3306/miaosha?serverTimezone=UTC
7     username: root
8     password: 1234
9     type: com.alibaba.druid.pool.DruidDataSource #数据源
10     driverClassName: com.mysql.jdbc.Driver
11   redis:
12     host: 10.0.75.1 #地址
13     port: 6379 #端口号
14     timeout: 20000 #连接超时时间
15   cache: #缓存类型
16     type: redis

 

第二步:在启动类上添加 @EnableCaching 注解

1 @SpringBootApplication(scanBasePackages = {"com.miaoshaproject"})
2 @MapperScan("com.miaoshaproject.dao")
3 @EnableCaching
4 public class App {
5
6     public static void main( String[] args ) {
7         ConfigurableApplicationContext run = SpringApplication.run(App.class, args);
8     }
9 }

第三步:在需要缓存的方法上添加 @Cacheable 注解

@Service
@CacheConfig(cacheNames = {"itemService"})
public class ItemServiceImpl implements ItemService {

@Override
@Cacheable(value = {"item"},key ="#p0")
public String getItemById(Integer id) {
String name = "123";
return name;
}
}

注:关于springboot缓存名的说明:

  使用SpringBoot缓存必须配置名字可以使用@CacheConfig(cacheNames = {"itemService"})在类上配置该类公用的名字,也可以使用@Cacheable(value=”item”)在方法上配置只适用于该方法的名字。如果类和方法上都有配置,以方法上的为准。

  springBoot会自动拼装缓存名,规则是:配置的名字+两个冒号+方法的实参;

注:关于@CacheConfig和@Cacheable注解的说明:

  @Cacheable(value=”item”),这个注释的意思是,当调用这个方法的时候,会从一个名叫 item 的缓存中查询,如果没有,则执行实际的方法(即查询数据库),并将执行的结果存入缓存中,否则返回缓存中的对象。
  在上面代码示例中@Cacheable注解设置了两个参数一个是value,一个是key。key的值"#p0"在执行过程中会被getItemById方法的实参所替换,例如id的值3 那么缓存的名字就会是"item::3";如果不设置key,系统会自动也会是这个效果。

  

 

  如果是无参方法:

  @CacheConfig is a class-level annotation that allows to share the cache names,如果你在你的方法写别的名字,那么依然以方法的名字为准。

转载于:https://www.cnblogs.com/zsukai/p/10428659.html

  • 点赞
  • 收藏
  • 分享
  • 文章举报
banxie7037 发布了0 篇原创文章 · 获赞 0 · 访问量 66 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: