Skip to content

SpringBoot使用@Cache整合Redis缓存.md

application.yml 缓存类型修改为 redis

yaml
spring:
  cache:
    type: redis

缓存配置类

java

@Configuration
@EnableCaching
public class RedisCacheConfiguration {

    public static final String XX_GROUP_KEY = "project:module:xx";

    @Bean
    public RedisCacheManagerBuilderCustomizer redisCacheManagerBuilderCustomizer() {
        return (builder) -> builder
                .withCacheConfiguration(XX_GROUP_KEY,
                        org.springframework.data.redis.cache.RedisCacheConfiguration.defaultCacheConfig()
                                .entryTtl(Duration.ofMinutes(5))
                                .disableCachingNullValues()
                                //变双冒号为单冒号
                                .computePrefixWith(name -> name + ":")
                                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(
                                        new Jackson2JsonRedisSerializer<>(List.class))));

    }
}

Mapper

java

@Mapper
@CacheConfig(cacheNames = RedisCacheConfiguration.XX_GROUP_KEY)
public interface XXMapper {

    @CacheEvict(allEntries = true, condition = "#result > 0")
    int insert(Entity e);

    @CacheEvict(allEntries = true, condition = "#result > 0")
    int update(Entity e);

    @Cacheable(key = "#root.methodName +':'+ #p0", unless = "#result == null")
    Entity selectOneByNo(@Param("no") String no);

    @Cacheable(key = "#root.methodName +':'+ #p0.hashCode()", unless = "#result == null || #result.size ==0")
    List<Entity> selectList(XXListQuery query);
}

单元测试

java
@RunWith(SpringRunner.class)
@ContextConfiguration
@SpringBootTest
public class CachingIntegrationTest {
    @Configuration
    @EnableCaching
    static class Config {
        @Bean
        CacheManager cacheManager() {
            return new ConcurrentMapCacheManager(XX_GROUP_KEY);
        }
        @Bean
        xxMapper xxMapper() {
            return Mockito.mock(xxMapper.class);
        }
    }

    @Autowired
    CacheManager manager;
    
    @Autowired
    XXMapper xxMapper;

    @Test
    public void methodInvocationShouldBeCached() {
        Vehicle vehicle = TestUtils.createObjAndFillFieldWithDefaultVal(Vehicle.class);
        Entity entity = TestUtils.createObjAndFillFieldWithDefaultVal(Entity.class);

        when(xxMapper.insert(any())).thenReturn(1);
        when(xxMapper.selectOneByNo(any())).thenReturn(entity);


        ConcurrentMapCache cache = (ConcurrentMapCache) manager.getCache(XX_GROUP_KEY);
        ConcurrentMap<Object, Object> nativeCache = cache.getNativeCache();
        
        mapper.selectOneByentityNo("s1");
        mapper.insert(new Entity());

        Assertions...
    }
}

文章来源于自己总结和网络转载,内容如有任何问题,请大佬斧正!联系我