zhuangjinxin / study

每日学习笔记
0 stars 0 forks source link

spring-boot-starter-cache 操作 Redis #2

Open zhuangjinxin opened 5 years ago

zhuangjinxin commented 5 years ago

今日收获:

  1. 知道Cache支持Generic、JCache (JSR-107)、EhCache 2.x、Hazelcast、Infinispan、Redis、Guava、Simple等;
  2. 知道以下注解的用法:@CacheConfig、@Cacheable、@CachePut、@CacheEvict();
zhuangjinxin commented 5 years ago

添加依赖:

<dependencies>
    <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>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

添加配置:

spring.redis.port=6379
spring.redis.host=127.0.0.1
spring.cache.cache-names=c1

启动类 开启缓存:

@SpringBootApplication 
@EnableCaching 
public class RediscacheApplication { 

    public static void main(String[] args) { 
        SpringApplication.run(RediscacheApplication.class, args); 
    } 
} 

自动配置:

@Configuration 
@ConditionalOnClass(RedisConnectionFactory.class) 
@AutoConfigureAfter(RedisAutoConfiguration.class) 
@ConditionalOnBean(RedisConnectionFactory.class) 
@ConditionalOnMissingBean(CacheManager.class) 
@Conditional(CacheCondition.class) 
class RedisCacheConfiguration { 

    @Bean 
    public RedisCacheManager cacheManager(RedisConnectionFactory redisConnectionFactory, ResourceLoader resourceLoader) { 
        RedisCacheManagerBuilder builder = RedisCacheManager.builder(redisConnectionFactory).cacheDefaults(determineConfiguration(resourceLoader.getClassLoader())); 
        List cacheNames = this.cacheProperties.getCacheNames(); 
        if (!cacheNames.isEmpty()) { 
            builder.initialCacheNames(new LinkedHashSet<>(cacheNames)); 
        } 
        return this.customizerInvoker.customize(builder.build()); 
    } 
} 

缓存使用:

@Service 
@CacheConfig(cacheNames = "c1") 
public class UserService { 

    @Cacheable(key = "#id") 
    public User getUserById(Integer id,String username) { 
        System.out.println("getUserById"); 
        return getUserFromDBById(id); 
    }

    @CachePut(key = "#user.id") 
    public User updateUserById(User user) { 
        return user; 
    }

    @CacheEvict() 
    public void deleteUserById(Integer id) { 
        //在这里执行删除操作, 删除是去数据库中删除 
    } 
} 
zhuangjinxin commented 5 years ago

参考文章: Spring Boot中,Redis缓存还能这么用!