Так что у меня есть небольшая проблема с точки зрения Redis. Похоже, что Springboot отказывается использовать пользовательский бон Rediscachemanager, который я создал, несмотря на то, что я использовал подходящие аннотации («@bean», «@primary») и вместо этого по умолчанию к общему. Это приводит к Jsonserializer, который я установил в пользовательском Cachemanager, не используемом, и Springboot Defliting для использования DefalteSerializer, как видно в трассировке стека в Pastebin. Класс MANAPPLICATION сканирует базовую часть, так что это не является проблемой структурирования кода, как распознаются все другие конфигурации в том же пакете. В чем может быть проблема? < /P>
Pastebins ниже. Любое исправление справки будет оценено.@Configuration
@EnableCaching
public class RedisConfig {
@Bean
public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) {
Jackson2JsonRedisSerializer jacksonSerializer =
new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
objectMapper.activateDefaultTyping(
objectMapper.getPolymorphicTypeValidator(),
ObjectMapper.DefaultTyping.NON_FINAL
);
jacksonSerializer.setObjectMapper(objectMapper);
RedisTemplate redisTemplate = new RedisTemplate();
redisTemplate.setConnectionFactory(redisConnectionFactory);
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(jacksonSerializer);
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setHashValueSerializer(jacksonSerializer);
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
@Bean(name = "cacheManager")
@Primary
public RedisCacheManager cacheManager(RedisTemplate redisTemplate) {
RedisCacheWriter redisCacheWriter = RedisCacheWriter.
nonLockingRedisCacheWriter(Objects.requireNonNull(redisTemplate.getConnectionFactory()));
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
.serializeValuesWith
(RedisSerializationContext.SerializationPair.
fromSerializer(redisTemplate.getValueSerializer()));
return RedisCacheManager.builder()
.cacheWriter(redisCacheWriter)
.cacheDefaults(redisCacheConfiguration)
.withCacheConfiguration("bitcoin-balances",
RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofMinutes(5)))
.withCacheConfiguration("ethereum-balances",
RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofMinutes(5)))
.withCacheConfiguration("bitcoinTransactions",
RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofHours(1)))
.withCacheConfiguration("ethereumTransactions",
RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofHours(1)))
.build();
}
}
< /code>
Журналы тестирования, которые показывают Cachemanager, используемый Springboot: < /p>
private final ApplicationContext applicationContext;
private final CacheManager cacheManager;
@PostConstruct
public void printCacheManager() {
System.out.println("Using CacheManager: " + cacheManager.getClass().getName());
}
@PostConstruct
public void listAllCacheManagers() {
String[] beans = applicationContext.getBeanNamesForType(CacheManager.class);
for (String bean : beans) {
System.out.println("CacheManager Bean: " + bean + " -> " + applicationContext.getBean(bean));
}
}
< /code>
Результаты: < /p>
Using CacheManager: org.springframework.data.redis.cache.RedisCacheManager
CacheManager Bean: cacheManager -> org.springframework.data.redis.cache.RedisCacheManager@408bb173
< /code>
Объект, используемый в качестве возвращаемого значения: < /p>
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class WalletDto {
private String address;
private BigDecimal balance;
}
< /code>
Метод, используемый в тесте: < /p>
@Cacheable(
value = "ethereum-balances",
key = "T(org.springframework.security.core.context.SecurityContextHolder).getContext().getAuthentication().getName()"
)
public WalletDto getWalletBalance() {
User user = authService.getCurrentUser();
EthereumWallet ethereumWallet = ethereumWalletRepository.findByUser(user)
.orElseThrow(
() -> new EntityNotFoundException("User does not have an Ethereum wallet"));
if (ethereumWallet.isTradingLocked()) {
throw new WalletLockedException("Wallet is currently in a transaction, try again later");
}
String address = ethereumWallet.getAddress();
BigInteger updatedBalanceWei = getBalance(address);
BigDecimal updatedBalanceEth = Converter.convertWeiToEth(updatedBalanceWei);
return WalletDto.builder()
.address(address)
.balance(updatedBalanceEth)
.build();
}
< /code>
Образец трассировки стека: < /p>
org.springframework.data.redis.serializer.SerializationException: Cannot serialize; nested exception is org.springframework.core.serializer.support.SerializationFailedException: Failed to serialize object using DefaultSerializer; nested exception is java.lang.IllegalArgumentException: DefaultSerializer requires a Serializable payload but received an object of type [com.kollybistes.common.dtos.WalletDto]
at org.springframework.data.redis.serializer.JdkSerializationRedisSerializer.serialize(JdkSerializationRedisSerializer.java:96)
at org.springframework.data.redis.serializer.DefaultRedisElementWriter.write(DefaultRedisElementWriter.java:44)
at org.springframework.data.redis.serializer.RedisSerializationContext$SerializationPair.write(RedisSerializationContext.java:287)
at org.springframework.data.redis.cache.RedisCache.serializeCacheValue(RedisCache.java:282)
at org.springframework.data.redis.cache.RedisCache.put(RedisCache.java:168)
at org.springframework.cache.interceptor.AbstractCacheInvoker.doPut(AbstractCacheInvoker.java:87)
at org.springframework.cache.interceptor.CacheAspectSupport$CachePutRequest.apply(CacheAspectSupport.java:837)
at org.springframework.cache.interceptor.CacheAspectSupport.execute(CacheAspectSupport.java:430)
at org.springframework.cache.interceptor.CacheAspectSupport.execute(CacheAspectSupport.java:345)
at org.springframework.cache.interceptor.CacheInterceptor.invoke(CacheInterceptor.java:64)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:753)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:698)
at com.kollybistes.core.services.EthereumService$$EnhancerBySpringCGLIB$$c3c3bd41.getWalletBalance()
Подробнее здесь: https://stackoverflow.com/questions/795 ... chemanager