我的项目在春季自定义OAuth2,所以当用户登录时,我返回自定义访问和刷新令牌并将其保存到缓存(这里我使用redis进行缓存)。我的Redis配置是:
@Configuration
public class CachingConfiguration {
@Autowired
private RedisConfigureSerializer configureSerializer;
@Bean
public RedisConnectionFactory jedisConnectionFactory() {
GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
poolConfig.setMaxTotal(100);
poolConfig.setBlockWhenExhausted(false);
RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
redisStandaloneConfiguration.setHostName("localhost");
redisStandaloneConfiguration.setPort(6379);
jedisClientConfiguration = JedisClientConfiguration.builder();
jedisClientConfiguration.usePooling();
jedisClientConfiguration.build();
JedisConnectionFactory jedisConFactory = new JedisConnectionFactory(redisStandaloneConfiguration,
jedisClientConfiguration
.usePooling()
.poolConfig(poolConfig)
.build());
return jedisConFactory;
}
@Bean
public RedisTemplate<String, Object> redisTemplate() {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(jedisConnectionFactory());
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(configureSerializer);
return template;
}
@Bean
public RedisCacheManager cacheManager() {
Map<String, RedisCacheConfiguration> map = new HashedMap();
map.put("accessTokenCache", redisCacheConfiguration());
RedisCacheManager cacheManager = RedisCacheManager.builder(RedisCacheWriter.lockingRedisCacheWriter(jedisConnectionFactory()))
.withInitialCacheConfigurations(map)
.transactionAware()
.build();
return cacheManager;
}
private RedisCacheConfiguration redisCacheConfiguration() {
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofDays(duration))
.disableCachingNullValues();
return config;
}
Class实现缓存
@EnableCaching
public class RedisCaching implements TokenStore, InitializingBean {
accessTokenCache = redisCacheManager.getCache("accessTokenCache");
accessTokenCache.put("1", "Hello1");//in debug mode, i put data in to cach and get value, it's ok
@Override
public void storeAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) {
accessTokenCache.put("2", "Hello2");//in debug mode, i put data into cach ok but get value by key return null value
}
}