spring boot2.x cache —— redis

引入pom文件


```java

    org.springframework.boot
    spring-boot-starter-cache


## **yml配置**

```java
spring:
  redis:
    host: 0.0.0.1
    password:123
    port: 4379
    timeout: 10000ms
    jedis:
      pool:
        max-active: 1024
        max-idle: 200
        max-wait: 10000ms
    database: 1

实现 CacheConfig类

/**
 * @Author KeXin
 * @Date 2019/6/19 下午6:32
 **/
@EnableCaching
@Configuration
public class CacheConfig extends CachingConfigurerSupport {
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory factory) {
        Map<String, RedisCacheConfiguration> initialCacheConfiguration = new LinkedHashMap<>();
        // spring boot2.0之后不支持直接setExpire
        addCache(initialCacheConfiguration, "offLineCache", 2);
    
        return RedisCacheManager.builder(factory)
                .withInitialCacheConfigurations(initialCacheConfiguration)
                .transactionAware()
                .build();
    
    }

    private void addCache(Map<String, RedisCacheConfiguration> initialCacheConfiguration, String cacheName, long ttl){
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofSeconds(ttl))
                .disableCachingNullValues()
                .prefixKeysWith(cacheName);
        initialCacheConfiguration.put(cacheName,config);
    }

    @Override
    @Bean
    public KeyGenerator keyGenerator() {
        return (o, method, params) -> {
            //本类名+方法名+参数名 为key
            StringBuilder sb = new StringBuilder();
            sb.append(o.getClass().getName());
            sb.append("-");
            sb.append(method.getName());
            sb.append("-");
            for (Object param : params) {
                sb.append(param.toString());
            }
            return sb.toString();
        };
    }
}

测试controller实现

package com.kexin.ehcache.controller;

import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
 * @Author KeXin
 * @Date 2019/06/20 下午6:17
 **/
@RestController
@RequestMapping("test")
public class TestController {
    @RequestMapping("/e-get")
    @Cacheable(value = "offLineCache", key = "#key")
    public String get(String key){
        System.out.println("未走echache");
        return key.hashCode()+"";
    }
}

常用注解

spring boot2.x cache —— redis_第1张图片

你可能感兴趣的:(数据库+缓存)