zoukankan      html  css  js  c++  java
  • Spring Cache 应用

    这节我们主要从应用的角度上,讲解下spring Cache在项目的应用。

    1、首先引入spring cache的jar包,最好引入下第三方的缓存jar包

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-cache</artifactId>
    </dependency>

    <dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>28.0-jre</version>
    </dependency>

     2、开启缓存注解--EnableCaching

    @EnableCaching
    public class Application {

    public static void main(String[] args) {
    // aes();
    // testJson();
    SpringApplication.run(Application.class, args);
    }
    }

    3、自定义CacheManager
    
    
    @Configuration
    public class CacheConfig {
    
    
        @Bean
        @Primary
        public GuavaCacheManager guavaCacheManager() {
            GuavaCacheManager guavaCacheManager = new GuavaCacheManager() {
                /**
                 * 设置数量限制、超时时间
                 * @param name
                 * @return
                 */
                @Override
                protected com.google.common.cache.Cache<Object, Object> createNativeGuavaCache(String name) {
                    return CacheBuilder.newBuilder()
                            .maximumSize(1000)
                            .expireAfterWrite(24, TimeUnit.HOURS)
                            .build();
                }
            };
            guavaCacheManager.setAllowNullValues(false);
            return guavaCacheManager;
        }
    
    }

    4、缓存使用
        @GetMapping
        @ApiOperation("")
        @Cacheable(key = "'templates'", cacheNames = "templates")
        public List<Template> obtain() throws Exception {
            String result = restService.getInfo(tUrl, HttpMethod.GET, headService.headers(null), false, false);
            JsonNode root = mapper.readTree(result);
            JavaType javaType = mapper.getTypeFactory().constructParametricType(List.class, Template.class);
            List<Template> list = (List<Template>) mapper.readValue(root.get("root").get("template").toString(), javaType);
            return list;
        }
     上述代码在第一次的时候,会执行方法中的逻辑,当第二次的时候,变回通过缓存进行获取。




  • 相关阅读:
    Poj 1742 Coins(多重背包)
    Poj 2350 Above Average(精度控制)
    求二进制数中1的个数
    Poj 1659 Distance on Chessboard(国际象棋的走子规则)
    Poj 2411 Mondriaan's Dream(压缩矩阵DP)
    Poj 2136 Vertical Histogram(打印垂直直方图)
    Poj 1401 Factorial(计算N!尾数0的个数——质因数分解)
    poj 2390 Bank Interest(计算本利和)
    Poj 2533 Longest Ordered Subsequence(LIS)
    Poj 1887 Testing the CATCHER(LIS)
  • 原文地址:https://www.cnblogs.com/sunxianbiao/p/12769452.html
Copyright © 2011-2022 走看看