whycxzp
2021-04-15 e4e8380597b5abdd2ede656cf5291c5d760b1149
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package com.whyc.config;
 
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.cache.CacheManager;
import org.springframework.cache.caffeine.CaffeineCache;
import org.springframework.cache.support.SimpleCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
 
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
 
/**
 * Caffeine配置
 */
@Configuration
public class CaffeineConfig {
 
    public static enum Caches{
        defaultCache(500),
        defaultCache2Exp(500,24)
        ;
 
        Caches() {
        }
 
        Caches(int maxSize) {
            this.maxSize = maxSize;
        }
 
        Caches(int maxSize, int ttl) {
            this.maxSize = maxSize;
            this.ttl = ttl;
        }
 
        private int maxSize;
        private int ttl;
 
        public int getMaxSize() {
            return maxSize;
        }
 
        public void setMaxSize(int maxSize) {
            this.maxSize = maxSize;
        }
 
        public int getTtl() {
            return ttl;
        }
 
        public void setTtl(int ttl) {
            this.ttl = ttl;
        }
    }
 
    @Bean
    @Primary
    public CacheManager caffeineCacheManager() {
        SimpleCacheManager cacheManager = new SimpleCacheManager();
        ArrayList<CaffeineCache> caffeineCaches = new ArrayList<>();
 
        for (Caches cache : Caches.values()) {
            caffeineCaches.add(new CaffeineCache(cache.name(),
                    Caffeine.newBuilder().recordStats()
                    .maximumSize(cache.getMaxSize())
                    .build()
            ));
        }
        cacheManager.setCaches(caffeineCaches);
        return cacheManager;
 
    }
 
    /*@Bean(value = "defaultCache")
    public Cache<String,Object> defaultCache(){
        return Caffeine.newBuilder().recordStats()
                        .maximumSize(Caches.defaultCache.getMaxSize())
                        .build();
    }
 
    @Bean(value = "defaultCache2Exp")
    public Cache<String,Object> defaultCache2Exp(){
        return Caffeine.newBuilder().recordStats()
                        .maximumSize(Caches.defaultCache2Exp.getMaxSize())
                        .expireAfterWrite(Caches.defaultCache2Exp.ttl, TimeUnit.HOURS)
                        .build();
    }*/
 
}