今天天看这个发现 ecache 对多线程的处理还要自己加锁来处理,Guava cache 是有问题的,现在最新的caffeine是不要再加锁来处理。
https://softwaremill.com/race-condition-cache-guava-caffeine/
我空我写个测试来测一下上边的问题,现用caffeine做个对比,现在没空先记录一下。
http://www.manongjc.com/article/48915.html
这个是使用caffeine的好文章。
来个测试用例吧:
1.
org.springframework.bootspring-boot-starter-cachecom.github.ben-manes.caffeinecaffeine2.6.2>
2.
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.CaffeineSpec;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;@Configuration
@EnableCaching
public class InitConfig {private static final Logger logger = LoggerFactory.getLogger(InitConfig.class);/*** caffeine CacheManager* @return*/@Bean("caffeine")public CacheManager cacheManager() {String caffeineSpec = "initialCapacity=50,maximumSize=500,refreshAfterWrite=10s";CaffeineSpec spec = CaffeineSpec.parse(caffeineSpec);Caffeine caffeine = Caffeine.from(spec);CaffeineCacheManager cacheManager = new CaffeineCacheManager();cacheManager.setCaffeine(caffeine);cacheManager.setAllowNullValues(false);CacheLoader cacheLoader = key -> null;cacheManager.setCacheLoader(cacheLoader);return cacheManager;}
}
3. 单独调用( 10s 后过期 ):
import org.springframework.cache.CacheManager;
import org.springframework.test.context.junit4.SpringRunner;import javax.annotation.Resource;@RunWith(SpringRunner.class)
@SpringBootTest
public class Demo2ApplicationTests {@Resource@Qualifier("caffeine")private CacheManager cacheManager;@Testpublic void contextLoads() {while(true){//System.out.println(cacheManager.getCacheNames());Cache cache = cacheManager.getCache("");if ( cache != null ) {String s = cache.get("123", String.class);System.out.println(s);if ( s == null ) {cache.put("123", "456");String s1 = cache.get("123", String.class);System.out.println( "null....."+s1 );}System.out.println(s);}try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}}}}