第一步:配置redis
这里使用的是yml类型的配置文件
mybatis:
mapper-locations: classpath:mapping/*.xml
spring:
datasource:
name: miaosha
url: jdbc:mysql://127.0.0.1:3306/miaosha?serverTimezone=UTC
username: root
password: 1234
type: com.alibaba.druid.pool.DruidDataSource #数据源
driverClassName: com.mysql.jdbc.Driver
redis:
host: 10.0.75.1 #地址
port: 6379 #端口号
timeout: 20000 #连接超时时间
cache: #缓存类型
type: redis
第二步:在启动类上添加 @EnableCaching 注解
@SpringBootApplication(scanBasePackages = {"com.miaoshaproject"})
@MapperScan("com.miaoshaproject.dao")
@EnableCaching
public class App { public static void main( String[] args ) {
ConfigurableApplicationContext run = SpringApplication.run(App.class, args);
}
}
第三步:在需要缓存的方法上添加 @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,如果你在你的方法写别的名字,那么依然以方法的名字为准。