SpringBoot应用之分布式缓存

SpringBoot应用系列文章

本文主要讲怎么在SpringBoot中集成redis,以及使用redis的缓存以及高效的集合操作功能。

准备redis

具体查看docker搭建redis集群这篇文章,该篇搭建了一主三从的redis集群。

新建项目

图片描述

集成redis

spring.redis.database=0
spring.redis.host=192.168.99.100
#spring.redis.password= # Login password of the redis server.
spring.redis.pool.max-active=8
spring.redis.pool.max-idle=8
spring.redis.pool.max-wait=-1
spring.redis.pool.min-idle=0
spring.redis.port=6379
#spring.redis.sentinel.master= # Name of Redis server.
#spring.redis.sentinel.nodes= # Comma-separated list of host:port pairs.
spring.redis.timeout=10

简单操作

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = RedisdemoApplication.class)
public class RedisdemoApplicationTests {

    @Autowired
    private StringRedisTemplate template;

    @Autowired
    private DemoService demoService;

    @Test
    public void set(){
        String key = "test-add";
        String value = "hello";
        template.opsForValue().set(key,value);
        assertEquals(value,template.opsForValue().get(key));
    }

    @Test
    public void incr(){
        String key = "test-incr";
        template.opsForValue().increment(key, 1);
        assertEquals(template.opsForValue().get(key),"1");
    }

    @Test
    public void should_not_cached(){
        demoService.getMessage("hello");
    }

    @Test
    public void should_cached(){
        demoService.getMessage("cat");
    }

    @Test
    public void should_cache_bean(){
        ReportBean b1 = demoService.getReport(1L, "2016-01-30", "hello", "world");
        ReportBean b2 = demoService.getReport(1L, "2016-01-30", "hello", "world");
    }

}

使用缓存

指定序列化

@SpringBootApplication
@EnableCaching
public class RedisdemoApplication {

    /**
     * 设置缓存对象的序列化方式,不设置会报错
     * 另外对于json序列化,对象要提供默认空构造器
     * @param redisTemplate
     * @return
     */
    @Bean
    public CacheManager cacheManager(RedisTemplate redisTemplate) {

        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);

        RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
        cacheManager.setDefaultExpiration(300);
        return cacheManager;
    }

    /**
     * 自定义key的生成策略
     * @return
     */
    @Bean
    public KeyGenerator myKeyGenerator(){
        return new KeyGenerator() {
            @Override
            public Object generate(Object target, Method method, Object... params) {
                StringBuilder sb = new StringBuilder();
                sb.append(target.getClass().getName());
                sb.append(method.getName());
                for (Object obj : params) {
                    sb.append(obj.toString());
                }
                return sb.toString();
            }
        };
    }

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

使用实例

@Component
public class DemoService {

    /**
     * Using SpEL for conditional caching - only cache method executions when
     * the name is equal to "Joshua"
     */
    @Cacheable(value="messageCache", condition="'cat'.equals(#name)")
    public String getMessage(String name) {
        System.out.println("Executing DemoService" +
                ".getHelloMessage(\"" + name + "\")");

        return "Hello " + name + "!";
    }

    @Cacheable(value = "reportcache",keyGenerator = "myKeyGenerator")
    public ReportBean getReport(Long id, String date, String content, String title) {
        System.out.println("无缓存的时候调用这里---数据库查询");
        return new ReportBean(id, date, content, title);
    }
}

参考

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值