1-2 添加缓存 Springboot 基于注解的缓存

1、使用情况

缓存的适用情况:查询内容长久不变的、读写比很大的(读写1:10)前后端一致性需求不高的 可以使用缓存

方法一 Springboot基于注解的缓存 @EnableCaching(proxyTargetClass=true) //开启支持缓存的注解 并基于类进行代理

常用注解:

@Cacheable //添加缓存 public List<User> findAllUser(){return list}

@CacheEvict //清理缓存 public void reloadUser(){}

@CachePut

@Caching

@CacheConfig

缺点:不能配置超时时间

 

方法二 Springboot基于Redis进行缓存  (可以设置过期时间)

application.properties 一定要设置过期时间

spring.cache.type=redis 
spring.cache.cache-names=user
spring.cache.redis.time-to-live=5000 
spring.cache.redis.cache-null-values=false 
spring.redis.host=192.168.114.131 

pom依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
@CacheConfig(cacheNames = "user")
@Service
public class UserServiceImpl {
    @Autowired
    UserRepository userRepository;

    @Cacheable
    public List<User> findAll(){
        return userRepository.findAll();
    }

    @CacheEvict
    public void reloadUser(){}
    
}



@SpringBootApplication
@EnableCaching(proxyTargetClass = true)
public class RibiApplication implements ApplicationRunner {

	public static void main(String[] args) {
		SpringApplication.run(RibiApplication.class, args);
	}
	
	@Autowired
	private UserServiceImpl service;

    @Override
    public void run(ApplicationArguments args) throws Exception{
        service.findAll().stream().forEach(x->{System.out.print(x);});
        for (int i=0;i<10;i++){
            service.findAll().stream().forEach(x->{System.out.print(x);});
        }
        service.reloadUser();
        service.findAll().stream().forEach(x->{System.out.print(x);});
    }
}

运行期间查看redis

127.0.0.1:6379> keys *
(empty list or set)
127.0.0.1:6379> keys *
1) "user::SimpleKey []"

已存在于redis

-- 部分摘自 极客时间 玩转Spring全家桶 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值