资讯专栏INFORMATION COLUMN

SpringBoot应用之分布式缓存

zhaot / 368人阅读

摘要:应用系列文章应用之配置中心应用之分布式会话应用之分布式索引应用之分布式缓存应用之消息队列应用之序本文主要讲怎么在中集成,以及使用的缓存以及高效的集合操作功能。

SpringBoot应用系列文章

SpringBoot应用之配置中心

SpringBoot应用之分布式会话

SpringBoot应用之分布式索引

SpringBoot应用之分布式缓存

SpringBoot应用之消息队列

SpringBoot应用之ELK

本文主要讲怎么在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);
    }
}
参考

Spring Boot使用redis做数据缓存

Caching with Spring Data Redis

Caching Data in Spring Using Redis

Redis 在 Spring-boot 中使用介绍

删除redis所有KEY

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/36155.html

相关文章

  • Springboot应用缓存实践:Ehcache加持

    摘要:但本文将讲述如何将缓存应用到应用中。这是的使用注解之一,除此之外常用的还有和,分别简单介绍一下配置在方法上表示其返回值将被加入缓存。 showImg(https://segmentfault.com/img/remote/1460000016643568); 注: 本文首发于 博客 CodeSheep · 程序羊,欢迎光临 小站!本文共 851字,阅读大约需要 3分钟 ! 本文内...

    luzhuqun 评论0 收藏0
  • 2019年java架构师视频

    摘要:并发专题一内存模型原理实现机制单例模式并发基础并发集合原子操作基本类型线程池互联网工程专题二简介安装工具编程介绍,入门程序仓库依赖管理简介常用操作命令 01.并发专题(一)2018-09-11(1)-Java内存模型2018-09-13(2)-synchronized原理2018-09-16(3)-volatile实现机制2018-09-18(4)-DCL-单例模式2018-09-21...

    Object 评论0 收藏0
  • SpringBoot应用ELK

    摘要:应用系列文章应用之配置中心应用之分布式会话应用之分布式索引应用之分布式缓存应用之消息队列应用之序本文主要讲怎么在里头配置输出到,使用技术栈实时查看日志。参考下使用或生成符合标准的格式 SpringBoot应用系列文章 SpringBoot应用之配置中心 SpringBoot应用之分布式会话 SpringBoot应用之分布式索引 SpringBoot应用之分布式缓存 SpringBoo...

    warkiz 评论0 收藏0
  • SpringBoot应用布式会话

    摘要:应用系列文章应用之配置中心应用之分布式会话应用之分布式索引应用之分布式缓存应用之消息队列应用之序本文主要讲怎么在应用里头搭建分布式会话。表示秒,即分钟,默认分钟过期。 SpringBoot应用系列文章 SpringBoot应用之配置中心 SpringBoot应用之分布式会话 SpringBoot应用之分布式索引 SpringBoot应用之分布式缓存 SpringBoot应用之消息队列...

    joy968 评论0 收藏0
  • SpringBoot应用布式索引

    摘要:应用系列文章应用之配置中心应用之分布式会话应用之分布式索引应用之分布式缓存应用之消息队列应用之序本文主要讲怎么在中使用。呢,从其根源来讲,是索引服务,但是讲高端一点,就是分布式的实时文件存储分布式的实时分析搜索引擎。 SpringBoot应用系列文章 SpringBoot应用之配置中心 SpringBoot应用之分布式会话 SpringBoot应用之分布式索引 SpringBoot应...

    mumumu 评论0 收藏0

发表评论

0条评论

zhaot

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<