我们正在调用身份联合服务来非常频繁地获取用户令牌,并且几乎在身份服务上运行负载测试。
一个潜在的解决方案是在现有应用程序中缓存用户令牌,但是使用本机spring-cache,我们可以使单个缓存条目到期吗?
在下面的例子中,我能够清除缓存,删除所有条目,但是我试图使单个条目到期。
@Service
@CacheConfig(cacheNames = {"userTokens"})
public class UserTokenManager {
static HashMap<String, String> userTokens = new HashMap<>();
@Cacheable
public String getUserToken(String userName){
String userToken = userTokens.get(userName);
if(userToken == null){
// call Identity service to acquire tokens
System.out.println("Adding UserName:" + userName + " Token:" + userToken);
userTokens.put(userName, userToken);
}
return userToken;
}
@CacheEvict(allEntries = true, cacheNames = { "userTokens"})
@Scheduled(fixedDelay = 3600000)
public void removeUserTokens() {
System.out.println("##############CACHE CLEANING##############, " +
"Next Cleanup scheduled at : " + new Date(System.currentTimeMillis()+ 3600000));
userTokens.clear();
}
}
Spring-boot应用程序类如下:
@SpringBootApplication
@EnableCaching
@EnableScheduling
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
通过在获取缓存键的方法上使用@CacheEvict
,可以使单个缓存条目到期。此外,通过使用Spring的缓存和@Cacheable
,不需要HashMap代码(因为它实际上只是一个二级缓存)。
@Service
@CacheConfig(cacheNames = {"userTokens"})
public class UserTokenManager {
private static Logger log = LoggerFactory.getLogger(UserTokenManager.class);
@Cacheable(cacheNames = {"userTokens"})
public String getUserToken(String userName) {
log.info("Fetching user token for: {}", userName);
String token = ""; //replace with call for token
return token;
}
@CacheEvict(cacheNames = {"userTokens"})
public void evictUserToken(String userName) {
log.info("Evicting user token for: {}", userName);
}
@CacheEvict(cacheNames = {"userTokens"}, allEntries = true)
public void evictAll() {
log.info("Evicting all user tokens");
}
}
例如:
getUserToken("Joe") -> no cache, calls API
getUserToken("Alice") -> no cache, calls API
getUserToken("Joe") -> cached
evictUserToken("Joe") -> evicts cache for user "Joe"
getUserToken("Joe") -> no cache, calls API
getUserToken("Alice") -> cached (as it has not been evicted)
evictAll() -> evicts all cache
getUserToken("Joe") -> no cache, calls API
getUserToken("Alice") -> no cache, calls API
如果你想让你的令牌被缓存一段时间,你需要另外一个CacheManager
除了原生Spring之外。有许多缓存选项可以与Spring的@Cacheable
一起使用。我将举例说明使用Caffeine,一个用于Java 8的高性能缓存库。例如,如果您知道要将令牌缓存30分钟,那么您可能希望使用此路由。
首先,将以下依赖项添加到build.gradle
(或者如果使用Maven,请翻译以下内容并将其放入pom.xml
中)。请注意,您将需要使用最新版本或与当前Spring Boot版本匹配的版本。
compile 'org.springframework.boot:spring-boot-starter-cache:2.1.4'
compile 'com.github.ben-manes.caffeine:caffeine:2.7.0'
一旦你添加了这两个依赖项,你所要做的就是在caffeine
文件中配置application.properties
规范:
spring.cache.cache-names=userTokens
spring.cache.caffeine.spec=expireAfterWrite=30m
将expireAfterWrite=30m
改为你想要的生活价值。例如,如果您想要400秒,则可以将其更改为expireAfterWrite=400s
。
有用的链接:
Spring Cache Abstraction是一个抽象而不是实现,因此它根本不支持显式设置TTL,因为这是一个特定于实现的功能。例如,如果您的缓存由ConcurrentHashMap
支持,则它不能支持TTL开箱即用。
在您的情况下,您有2个选项。如果您需要的是本地缓存(即每个微服务实例管理自己的缓存),您可以使用Caffeine替换Spring Cache Abstraction,<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
</dependency>
是Spring Boot提供和管理的官方依赖项。只需要声明而不提及版本。
@Service
public class UserTokenManager {
private static Cache<String, String> tokenCache;
@Autowired
private UserTokenManager (@Value("${token.cache.time-to-live-in-seconds}") int timeToLiveInSeconds) {
tokenCache = Caffeine.newBuilder()
.expireAfterWrite(timeToLiveInSeconds, TimeUnit.SECONDS)
// Optional listener for removal event
.removalListener((userName, tokenString, cause) -> System.out.println("TOKEN WAS REMOVED FOR USER: " + userName))
.build();
}
public String getUserToken(String userName){
// If cached, return; otherwise create, cache and return
// Guaranteed to be atomic (i.e. applied at most once per key)
return tokenCache.get(userName, userName -> this.createToken(userName));
}
private String createToken(String userName) {
// call Identity service to acquire tokens
}
}
然后,您可以创建一个缓存实例,如下所示。您放入缓存的每个令牌都将根据您的配置自动删除。
EHCache
同样,这是一个本地缓存,这意味着每个微服务将管理他们自己的令牌集。因此,如果您运行相同微服务的5个实例,则同一用户可能在所有5个缓存中有5个令牌,具体取决于处理其请求的实例。
另一方面,如果您需要分布式缓存(即多个微服务实例共享相同的集中式缓存),您需要查看Hazelcast或CacheManager
。在这种情况下,您可以继续使用Spring Cache Abstraction,并通过从这些库中声明HazelcastCacheManager
(例如CacheManager
)来选择其中一个库作为您的实现。
然后,您可以查看相应的文档,以便针对特定缓存(例如,您的tokenCache
)进一步配置您选择的带有TTL的@Configuration
public class DistributedCacheConfiguration {
@Bean
public HazelcastInstance hazelcastInstance(@Value("${token.cache.time-to-live-in-seconds}") int timeToLiveInSeconds) {
Config config = new Config();
config.setInstanceName("hazelcastInstance");
MapConfig mapConfig = config.getMapConfig("tokenCache");
mapConfig.setTimeToLiveSeconds(timeToLiveInSeconds);
return Hazelcast.newHazelcastInstance(config);
}
@Bean
public CacheManager cacheManager(HazelcastInstance hazelcastInstance) {
return new HazelcastCacheManager(hazelcastInstance);
}
}
。我在下面为Hazelcast提供了一个简单的配置作为示例。
qazxswpoi