I am working on a small demo project for Redis and Spring Boot. But for the following GET endpoints I am getting ClassCastException.–
@GetMapping("/all")
public List<Product> getAllProducts(){
return productRepository.findAll();
}
@GetMapping("/product/{id}")
public Product finProduct(@PathVariable int id){
return productRepository.findProductById(id);
}
Serivces-
public List<Product> findAll() {
List<Product> products=new ArrayList<>();
redisTemplate.opsForHash().values(HASH_KEY).forEach(e->products.add((Product)e));
return products;
}
public Product findProductById(int id) {
return (Product) redisTemplate.opsForHash().get(HASH_KEY, id);
}
I am getting following error-
java.lang.ClassCastException: class com.ayushsingh.springdataredisdemo.entity.Product cannot be cast to class com.ayushsingh.springdataredisdemo.entity.Product (com.ayushsingh.springdataredisdemo.entity.Product is in unnamed module of loader 'app'; com.ayushsingh.springdataredisdemo.entity.Product is in unnamed module of loader org.springframework.boot.devtools.restart.classloader.RestartClassLoader @18f69edd)
I referred the following article: https://medium.com/javarevisited/classcast-exception-when-using-redis-and-springboot-frameworks-in-conjunction-ea132dd0d7ea, but still getting same error.
Beans-
@Configuration
@EnableRedisRepositories
public class RedisConfig {
// Connection Configuration
@Bean
public JedisConnectionFactory connectionFactory() {
RedisStandaloneConfiguration configuration = new RedisStandaloneConfiguration();
configuration.setHostName("localhost");
configuration.setPort(6379);
Duration readTimeout = Duration.ofMillis(30 * 1000);
Duration connectTimeout = Duration.ofMillis(3 * 1000);
JedisClientConfiguration clientConfiguration = JedisClientConfiguration.builder()
.readTimeout(readTimeout)
.connectTimeout(connectTimeout)
.usePooling()
.build();
JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(configuration, clientConfiguration);
return jedisConnectionFactory;
}
// Redis template to acces Redis server
@Bean
public RedisTemplate<String, Object> redisTemplate() {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(connectionFactory());
template.setKeySerializer(new StringRedisSerializer());
template.setHashKeySerializer(new StringRedisSerializer());
template.setHashKeySerializer(new JdkSerializationRedisSerializer(getClass().getClassLoader()));
template.setValueSerializer(new JdkSerializationRedisSerializer(getClass().getClassLoader()));
template.setEnableTransactionSupport(true);
template.afterPropertiesSet();
return template;
}
}
application properties-
spring.devtools.restart.enabled=false
server.port=8082
Please help!
2
Answers
I met the same error. The only way is to remove
spring-devtools
module. It seems like to be caused byClassLoader
. But I don’t know how to solve it. But removing this module really worked.try this way:
Reference Spring Doc