JBoss 7.1 and Hibernte 4.3.5 cause exception - jboss7.x

I create a project with Hibernate 4.3.5 and JBoss 7.1.1.
I give you a screenshot about the composition of my project:
The jars on WEB-INF/lib are:
Bellow, are the rquired classes:
EntityDao.java
public class EntityDao implements EntityDaoInterface<Book, Integer>
{
private Session currentSession;
private Transaction currentTransaction;
public EntityDao() {
}
public Session openCurrentSession() {
currentSession = getSessionFactory().openSession();
return currentSession;
}
public Session openCurrentSessionwithTransaction() {
currentSession = getSessionFactory().openSession();
currentTransaction = currentSession.beginTransaction();
return currentSession;
}
public void closeCurrentSession() {
currentSession.close();
}
public void closeCurrentSessionwithTransaction() {
currentTransaction.commit();
currentSession.close();
}
private static SessionFactory getSessionFactory() {
Configuration configuration = new Configuration().configure();
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties());
SessionFactory sessionFactory = configuration.buildSessionFactory(builder.build());
return sessionFactory;
}
public Session getCurrentSession() {
return currentSession;
}
public void setCurrentSession(Session currentSession) {
this.currentSession = currentSession;
}
public Transaction getCurrentTransaction() {
return currentTransaction;
}
public void setCurrentTransaction(Transaction currentTransaction) {
this.currentTransaction = currentTransaction;
}
public void persist(Person entity) {
getCurrentSession().save(entity);
}
public void update(Person entity) {
getCurrentSession().update(entity);
}
public void delete(Person entity) {
getCurrentSession().delete(entity);
}
#SuppressWarnings("unchecked")
public List<Person> findAllPersons() {
List<Person> persons = (List<Person>) getCurrentSession().createQuery("from Person").list();
return persons;
}
public Person findPersonById(Integer id) {
Person person = (Person) getCurrentSession().get(Person.class, id);
return person;
}
}
EntityDaoInterface.java
public interface EntityDaoInterface<T, Id extends Serializable>
{
public void persist(T entity);
public void update(T entity);
public T findById(Id id);
public void delete(T entity);
public List<T> findAll();
public void deleteAll();
}
EntityService.java
public class EntityService
{
private static EntityDao entityDao;
public EntityService() {
entityDao = new EntityDao();
}
public void persist(Person entity) {
entityDao.openCurrentSessionwithTransaction();
entityDao.persist(entity);
entityDao.closeCurrentSessionwithTransaction();
}
public void update(Person entity) {
entityDao.openCurrentSessionwithTransaction();
entityDao.update(entity);
entityDao.closeCurrentSessionwithTransaction();
}
public void remove(Person entity) {
entityDao.openCurrentSessionwithTransaction();
entityDao.delete(entity);
entityDao.closeCurrentSessionwithTransaction();
}
public Person findPersonById(int id) {
entityDao.openCurrentSession();
Person person = entityDao.findPersonById(id);
entityDao.closeCurrentSession();
return person;
}
public List<Person> findAllPersons() {
entityDao.openCurrentSession();
List<Person> persons = entityDao.findAllPersons();
entityDao.closeCurrentSession();
return persons;
}
public void deleteAll() {
entityDao.openCurrentSessionwithTransaction();
entityDao.deleteAll();
entityDao.closeCurrentSessionwithTransaction();
}
public EntityDao entityDao() {
return entityDao;
}
}
Person.java
#Entity
#Table(name = "person")
public class Person
{
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "id", unique = true, nullable = false)
private int id;
#Column(name = "age")
private int age;
#Column(name= "name")
String name;
public Person() {}
public Person(int id, int age, String name) {
super();
this.id = id;
this.age = age;
this.name = name;
}
// With the methods: set, get, toString, hashCode, equals
}
hibernate.cfg.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.SQLServer2008Dialect</property>
<property name="hibernate.connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
<property name="hibernate.connection.url">jdbc:sqlserver://localhost:1433;database=ccc</property>
<property name="hibernate.connection.username">lm</property>
<property name="hibernate.connection.password">pp</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="show_sql">true</property>
<property name="hibernate.current_session_context_class">thread</property>
<mapping class="com.esprit.entity.Book"/>
<mapping class="com.esprit.entity.Person"/>
</session-factory>
</hibernate-configuration>
DataModelBeanD.java
#SuppressWarnings("serial")
#ManagedBean
#ViewScoped
public class DataModelBeanD implements Serializable
{
private List<Person> list;
private Person person = new Person();
private boolean edit;
private EntityService entityService;
#PostConstruct
public void init()
{
entityService = new EntityService();
list = entityService.findAllPersons();
}
}
After running the project, the following error appears:
08:32:54,297 INFO [org.jboss.as.server] (DeploymentScanner-threads - 2) JBAS018559: Deployed "HelloJPAHibernate.war"
08:33:01,282 INFO [org.hibernate.annotations.common.Version] (http-localhost-127.0.0.1-8080-1) HCANN000001: Hibernate Commons Annotations {4.0.4.Final}
08:33:01,290 INFO [org.hibernate.Version] (http-localhost-127.0.0.1-8080-1) HHH000412: Hibernate Core {4.3.5.Final}
08:33:01,293 INFO [org.hibernate.cfg.Environment] (http-localhost-127.0.0.1-8080-1) HHH000205: Loaded properties from resource hibernate.properties: {hibernate.connection.driver_class=org.h2.Driver, hibernate.service.allow_crawling=false, hibernate.dialect=org.hibernate.dialect.H2Dialect, hibernate.max_fetch_depth=5, hibernate.format_sql=true, hibernate.generate_statistics=true, hibernate.connection.username=sa, hibernate.connection.url=jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1;MVCC=TRUE, hibernate.bytecode.use_reflection_optimizer=false, hibernate.jdbc.batch_versioned_data=true, hibernate.connection.pool_size=5}
08:33:01,297 INFO [org.hibernate.cfg.Environment] (http-localhost-127.0.0.1-8080-1) HHH000021: Bytecode provider name : javassist
08:33:01,317 INFO [org.hibernate.cfg.Configuration] (http-localhost-127.0.0.1-8080-1) HHH000043: Configuring from resource: /hibernate.cfg.xml
08:33:01,318 INFO [org.hibernate.cfg.Configuration] (http-localhost-127.0.0.1-8080-1) HHH000040: Configuration resource: /hibernate.cfg.xml
08:33:01,366 INFO [org.hibernate.cfg.Configuration] (http-localhost-127.0.0.1-8080-1) HHH000041: Configured SessionFactory: null
08:33:01,453 WARN [org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl] (http-localhost-127.0.0.1-8080-1) HHH000402: Using Hibernate built-in connection pool (not for production use!)
08:33:01,455 INFO [org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl] (http-localhost-127.0.0.1-8080-1) HHH000401: using driver [com.microsoft.sqlserver.jdbc.SQLServerDriver] at URL [jdbc:sqlserver://localhost:1433;database=ccc]
08:33:01,457 INFO [org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl] (http-localhost-127.0.0.1-8080-1) HHH000046: Connection properties: {user=lm, password=****}
08:33:01,458 INFO [org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl] (http-localhost-127.0.0.1-8080-1) HHH000006: Autocommit mode: false
08:33:01,460 INFO [org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl] (http-localhost-127.0.0.1-8080-1) HHH000115: Hibernate connection pool size: 5 (min=1)
08:33:03,123 INFO [org.hibernate.dialect.Dialect] (http-localhost-127.0.0.1-8080-1) HHH000400: Using dialect: org.hibernate.dialect.SQLServer2008Dialect
08:33:03,255 ERROR [org.apache.catalina.core.ContainerBase.[jboss.web].[default-host].[/HelloJPAHibernate].[Faces Servlet]] (http-localhost-127.0.0.1-8080-1) Servlet.service() for servlet Faces Servlet threw exception: java.lang.NoSuchMethodError: javax.persistence.Table.indexes()[Ljavax/persistence/Index;
at org.hibernate.cfg.annotations.EntityBinder.processComplementaryTableDefinitions(EntityBinder.java:936) [hibernate-core-4.3.5.Final.jar:4.3.5.Final]
at org.hibernate.cfg.AnnotationBinder.bindClass(AnnotationBinder.java:824) [hibernate-core-4.3.5.Final.jar:4.3.5.Final]
at org.hibernate.cfg.Configuration$MetadataSourceQueue.processAnnotatedClassesQueue(Configuration.java:3788) [hibernate-core-4.3.5.Final.jar:4.3.5.Final]
at org.hibernate.cfg.Configuration$MetadataSourceQueue.processMetadata(Configuration.java:3742) [hibernate-core-4.3.5.Final.jar:4.3.5.Final]
at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1410) [hibernate-core-4.3.5.Final.jar:4.3.5.Final]
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1844) [hibernate-core-4.3.5.Final.jar:4.3.5.Final]
at com.esprit.dao.EntityDao.getSessionFactory(EntityDao.java:48) [classes:]
at com.esprit.dao.EntityDao.openCurrentSession(EntityDao.java:25) [classes:]
at com.esprit.dao.EntityService.findAllPersons(EntityService.java:86) [classes:]
at com.esprit.crud.dynamic.DataModelBeanD.init(DataModelBeanD.java:37) [classes:]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [rt.jar:1.7.0_55]
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) [rt.jar:1.7.0_55]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) [rt.jar:1.7.0_55]
at java.lang.reflect.Method.invoke(Unknown Source) [rt.jar:1.7.0_55]
I couldn't know what's missed, could you please help me solving this issue. Any proposition is appreciated.Thanks in advance.

I solved my problem by making Hibernate 4.2.21 instead of Hibernate 4.3.5. Then I re-create the method getSessionFactory() of the class EntityDao.java like bellow:
private static SessionFactory getSessionFactory()
{
if (sessionFactory == null) {
Configuration configuration = new Configuration().configure();
ServiceRegistryBuilder registry = new ServiceRegistryBuilder();
registry.applySettings(configuration.getProperties());
ServiceRegistry serviceRegistry = registry.buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
}
return sessionFactory;
}

Related

Issue with #ConfigurationProperties while using spring-session with Redis

Not able to access the properties while using Spring-session with Redis.
Auto wiring is not happening hence this object is null. Not sure what wrong I'm doing here.
#Autowired
private RedisSentinelProperties redisSentinelProperties;
Without spring-session it works fine without any issue.
I have tried without spring-session and it works fine. Able to access the all the properties and Auto wiring happens properly
#Autowired
private RedisSentinelProperties redisSentinelProperties;
Custom properties configuration
#Component
#ConfigurationProperties(prefix = "app.redis")
#Validated
public class RedisSentinelProperties {
#NotNull
private String masterName;
#Valid
private Sentinel sentinel = new Sentinel();
////removed the getter and setter method for better readability
public static class Sentinel {
#NotEmpty
private List<String> nodes = new ArrayList<>();
//removed the getter and setter method for better readability
}
}
application.properties
app.redis.master-name=mymaster
app.redis.sentinel.nodes=192.168.56.50:26379,192.168.56.50:26380,192.168.56.50:26381
spring-session configuration
#SpringBootApplication
public class ConfigPropertiesDemoApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigPropertiesDemoApplication.class, args);
}
}
public class RedisHttpSessionInitializer extends AbstractHttpSessionApplicationInitializer {
public RedisHttpSessionInitializer() {
super(RedisHttpSessionConfig.class);
}
}
#Configuration
#EnableRedisHttpSession
#EnableWebSecurity
public class RedisHttpSessionConfig {
#Autowired
private RedisSentinelProperties redisSentinelProperties;
LettuceClientConfiguration clientConfig = LettuceClientConfiguration.builder()
.readFrom(SLAVE_PREFERRED)
.build();
private Set<String> sentinelHostAndPorts(){
Set<String> nodes = redisSentinelProperties.getSentinel().getNodes().stream().collect(Collectors.toSet());
return nodes;
}
//This is where NullPointerException is thrown line 37 in the stack trace
RedisSentinelConfiguration sentinelConfig = new RedisSentinelConfiguration(redisSentinelProperties.getMasterName(), sentinelHostAndPorts());
#Bean
public LettuceConnectionFactory connectionFactory() {
return new LettuceConnectionFactory(sentinelConfig, clientConfig);
}
}
Below is the stack trace
Caused by: java.lang.NullPointerException
at com.bt.consumer.configpropertiesdemo.config.RedisHttpSessionConfig.(RedisHttpSessionConfig.java:37)
at com.bt.consumer.configpropertiesdemo.config.RedisHttpSessionConfig$$EnhancerBySpringCGLIB$$f6d40824.()
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:172)

infinispan 9.4 - Listeners and event filter

I'm trying to use Listeners with filters in a distributed cache with two instances of Infinispan 9.4.0 and Hot Rod Client. When I try to put a new entry in cache, I get the following exception:
[Server:instance-one] 13:09:57,468 ERROR [stderr] (HotRod-ServerHandler-4-2) Exception in thread "HotRod-ServerHandler-4-2" org.infinispan.commons.CacheException: ISPN000936: Class 'com.cm.broadcaster.infinispan.entity.EntityDemo' blocked by deserialization white list. Adjust the configuration serialization white list regular expression to include this class.
This is the cache configuration:
<distributed-cache name="entityCache" remote-timeout="3000" statistics-available="false">
<memory>
<object size="20" strategy="LRU" />
</memory>
<compatibility enabled="true"/>
<file-store path="entity-store" passivation="true"/>
<indexing index="NONE"/>
<state-transfer timeout="60000" chunk-size="1024"/>
</distributed-cache>
This is my demo class:
public class EntityDemo implements Serializable {
private static final long serialVersionUID = 1L;
private long id;
private String name;
private String value;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
The EventFilterFactory:
#NamedFactory(name="entity-event-filter-factory")
public class EntityEventFilterFactory implements CacheEventFilterFactory {
#Override
public CacheEventFilter<String, EntityDemo> getFilter(Object[] params) {
return new EntityEventFilter(params);
}
}
The EventFilter:
public class EntityEventFilter implements Serializable, CacheEventFilter<String, EntityDemo> {
private static final long serialVersionUID = 1L;
private final long filter;
public EntityEventFilter(Object[] params) {
this.filter = Long.valueOf(String.valueOf(params[0]));
}
#Override
public boolean accept(String key, EntityDemo oldValue, Metadata oldMetadata, EntityDemo newValue, Metadata newMetadata, EventType eventType) {
if (eventType.isCreate()) {
if (oldValue.getId() % filter == 0)
return true;
}
return false;
}
}
My test code:
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.addServers("localhost:11222");
RemoteCacheManager rcm = new RemoteCacheManager(cb.build());
RemoteCache<String, EntityDemo> rc = rcm.<String,
EntityDemo>getCache("entityCache");
rc.addClientListener(new CustomListener(), new Object[]{"1"}, null);
EntityDemo e = new EntityDemo();
e.setId(1);
e.setName("Demo");
e.setValue("Demo");
rc.put("1", e);
The listener:
#ClientListener(filterFactoryName="entity-event-filter-factory")
public class CustomListener {
#ClientCacheEntryCreated
public void entryCreated(ClientCacheEntryCreatedEvent<String> event) {
System.out.println("Entry created!");
System.out.println(event.getKey());
}
}
I have looked about white list for serialization, but I have found nothing.
I tried changing object in memory configuration for binary and disabling compatibility, but then I get a new exception:
[Server:instance-one] 13:56:42,131 ERROR [org.infinispan.interceptors.impl.InvocationContextInterceptor] (HotRod-ServerHandler-4-2) ISPN000136: Error executing command PutKeyValueCommand, writing keys [WrappedByteArray{bytes=[B0x01012903033E0131, hashCode=1999574342}]: java.lang.ClassCastException: java.lang.String cannot be cast to com.cm.broadcaster.infinispan.entity.EntityDemo
Can anyone help me with this?
Have you tried this? Passing the -Dinfinispan.deserialization.whitelist.classes property to the server.
http://infinispan.org/docs/stable/upgrading/upgrading.html#deserialization_whitelist

Exception: java.io.NotSerializableException: org.springframework.jdbc.datasource.DriverManagerDataSource

I created a spring project (Spring 4.0.2). I present the required files:
spring.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="employeeDAO" class="com.journaldev.spring.jdbc.dao.EmployeeDAOImpl">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="employeeDAOJDBCTemplate" class="com.journaldev.spring.jdbc.dao.EmployeeDAOJDBCTemplateImpl">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver" />
<property name="url" value="jdbc:sqlserver://localhost:1433;database=springdb"/>
<property name="username" value="lm" />
<property name="password" value="pp" />
</bean>
</beans>
Employee.java
#Entity
#Table(name="Employee")
public class Employee {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name = "id", unique = true, nullable = false)
private int id;
#Column(name = "name")
private String name;
#Column(name = "role")
private String role;
// with getters, setters, default constructor, constructor using fields
}
EmployeeDAO.java
public interface EmployeeDAO
{
public List<Employee> getAll();
}
EmployeeDAOImpl.java
public class EmployeeDAOImpl implements EmployeeDAO {
private DataSource dataSource;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
#Override
public List<Employee> getAll() {
String query = "select id, name, role from Employee";
List<Employee> empList = new ArrayList<Employee>();
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try{
con = dataSource.getConnection();
ps = con.prepareStatement(query);
rs = ps.executeQuery();
while(rs.next()){
Employee emp = new Employee();
emp.setId(rs.getInt("id"));
emp.setName(rs.getString("name"));
emp.setRole(rs.getString("role"));
empList.add(emp);
}
}catch(SQLException e){
e.printStackTrace();
}finally{
try {
rs.close();
ps.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return empList;
}
}
EmployeeDAOJDBCTemplateImpl.java
public class EmployeeDAOJDBCTemplateImpl implements EmployeeDAO,Serializable {
private DataSource dataSource;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
#Override
public List<Employee> getAll() {
String query = "select id, name, role from Employee";
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
List<Employee> empList = new ArrayList<Employee>();
List<Map<String,Object>> empRows = jdbcTemplate.queryForList(query);
for(Map<String,Object> empRow : empRows){
Employee emp = new Employee();
emp.setId(Integer.parseInt(String.valueOf(empRow.get("id"))));
emp.setName(String.valueOf(empRow.get("name")));
emp.setRole(String.valueOf(empRow.get("role")));
empList.add(emp);
}
return empList;
}
}
The bean to call in order to extract the list of employees DataModelD.java :
#ManagedBean
#ViewScoped
public class DataModelD implements Serializable
{
private List<Employee> list;
private Employee employee;
private EmployeeDAO eDao;
#PostConstruct
public void init()
{
System.out.println("-----------------------------BEGIN List");
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");
eDao = ctx.getBean("employeeDAOJDBCTemplate", EmployeeDAO.class);
employee = new Employee();
list = eDao.getAll();
System.out.println("---------------------------------------List size= " + list.size());
}
}
After running it(to display the list of employees), the following exception is displayed:
08:14:46,222 INFO [org.jboss.as.server] (DeploymentScanner-threads - 2) JBAS018559: Deployed "HiSpring.war"
08:15:29,271 INFO [stdout] (http-localhost-127.0.0.1-8080-1) -----------------------------BEGIN List
08:15:29,529 INFO [org.springframework.context.support.ClassPathXmlApplicationContext] (http-localhost-127.0.0.1-8080-1) Refreshing org.springframework.context.support.ClassPathXmlApplicationContext#ca34ed: startup date [Wed Aug 17 08:15:29 GMT-08:00 2016]; root of context hierarchy
08:15:29,591 INFO [org.springframework.beans.factory.xml.XmlBeanDefinitionReader] (http-localhost-127.0.0.1-8080-1) Loading XML bean definitions from class path resource [spring.xml]
08:15:29,718 INFO [org.springframework.jdbc.datasource.DriverManagerDataSource] (http-localhost-127.0.0.1-8080-1) Loaded JDBC driver: com.microsoft.sqlserver.jdbc.SQLServerDriver
08:15:30,736 INFO [stdout] (http-localhost-127.0.0.1-8080-1) ---------------------------------------List size= 5
08:15:30,832 SEVERE [javax.enterprise.resource.webcontainer.jsf.application] (http-localhost-127.0.0.1-8080-1) Error Rendering View[/sarsoura/list.xhtml]: java.io.NotSerializableException: org.springframework.jdbc.datasource.DriverManagerDataSource
at java.io.ObjectOutputStream.writeObject0(Unknown Source) [rt.jar:1.7.0_55]
at java.io.ObjectOutputStream.defaultWriteFields(Unknown Source) [rt.jar:1.7.0_55]
Have you please any idea about this issue?.Any reply will be appreciated.

Set Gemfire entry-ttl in Java Beans

I would like to create a Gemfire region in a Spring Boot application. Following this sample, it works well wihout adding database support. If I add database, it will shows error like " Error creating bean with name 'dataSource'". However, default gemfire cache bean works well with datasource integration.
#EnableAutoConfiguration
// Sprint Boot Auto Configuration
#ComponentScan(basePackages = "napo.demo")
#EnableCaching
#SuppressWarnings("unused")
public class Application extends SpringBootServletInitializer {
private static final Class<Application> applicationClass = Application.class;
private static final Logger log = LoggerFactory.getLogger(applicationClass);
public static void main(String[] args) {
SpringApplication.run(applicationClass, args);
}
/* **The commented code works well with database.**
#Bean
CacheFactoryBean cacheFactoryBean() {
return new CacheFactoryBean();
}
#Bean
ReplicatedRegionFactoryBean<Integer, Integer> replicatedRegionFactoryBean(final Cache cache) {
ReplicatedRegionFactoryBean<Integer, Integer> region= new ReplicatedRegionFactoryBean<Integer, Integer>() {{
setCache(cache);
setName("demo");
}};
return region;
} */
// This configuration will cause issue as beow
//
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfiguration$NonEmbeddedConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.sql.DataSource]: Factory method 'dataSource' threw exception; nested exception is java.lang.NullPointerException
#Bean
GemfireCacheManager cacheManager(final Cache gemfireCache) {
return new GemfireCacheManager() {
{
setCache(gemfireCache);
}
};
}
// NOTE ideally, "placeholder" properties used by Spring's PropertyPlaceholderConfigurer would be externalized
// in order to avoid re-compilation on property value changes (so... this is just an example)!
#Bean
public Properties placeholderProperties() {
Properties placeholders = new Properties();
placeholders.setProperty("app.gemfire.region.eviction.action", "LOCAL_DESTROY");
placeholders.setProperty("app.gemfire.region.eviction.policy-type", "MEMORY_SIZE");
placeholders.setProperty("app.gemfire.region.eviction.threshold", "4096");
placeholders.setProperty("app.gemfire.region.expiration.entry.tti.action", "INVALIDATE");
placeholders.setProperty("app.gemfire.region.expiration.entry.tti.timeout", "300");
placeholders.setProperty("app.gemfire.region.expiration.entry.ttl.action", "DESTROY");
placeholders.setProperty("app.gemfire.region.expiration.entry.ttl.timeout", "60");
placeholders.setProperty("app.gemfire.region.partition.local-max-memory", "16384");
placeholders.setProperty("app.gemfire.region.partition.redundant-copies", "1");
placeholders.setProperty("app.gemfire.region.partition.total-max-memory", "32768");
return placeholders;
}
#Bean
public PropertyPlaceholderConfigurer propertyPlaceholderConfigurer(
#Qualifier("placeholderProperties") Properties placeholders) {
PropertyPlaceholderConfigurer propertyPlaceholderConfigurer = new PropertyPlaceholderConfigurer();
propertyPlaceholderConfigurer.setProperties(placeholders);
return propertyPlaceholderConfigurer;
}
#Bean
public Properties gemfireProperties() {
Properties gemfireProperties = new Properties();
gemfireProperties.setProperty("name", "SpringGemFireJavaConfigTest");
gemfireProperties.setProperty("mcast-port", "0");
gemfireProperties.setProperty("log-level", "config");
return gemfireProperties;
}
#Bean
#Autowired
public CacheFactoryBean gemfireCache(#Qualifier("gemfireProperties") Properties gemfireProperties) throws Exception {
CacheFactoryBean cacheFactory = new CacheFactoryBean();
cacheFactory.setProperties(gemfireProperties);
return cacheFactory;
}
#Bean(name = "ExamplePartition")
#Autowired
public ReplicatedRegionFactoryBean<Object, Object> examplePartitionRegion(Cache gemfireCache,
#Qualifier("partitionRegionAttributes") RegionAttributes<Object, Object> regionAttributes) throws Exception {
ReplicatedRegionFactoryBean<Object, Object> examplePartitionRegion =
new ReplicatedRegionFactoryBean<Object, Object>();
examplePartitionRegion.setAttributes(regionAttributes);
examplePartitionRegion.setCache(gemfireCache);
examplePartitionRegion.setName("demo");
return examplePartitionRegion;
}
#Bean
#Autowired
public RegionAttributesFactoryBean partitionRegionAttributes(
EvictionAttributes evictionAttributes,
#Qualifier("entryTtiExpirationAttributes") ExpirationAttributes entryTti,
#Qualifier("entryTtlExpirationAttributes") ExpirationAttributes entryTtl) {
RegionAttributesFactoryBean regionAttributes = new RegionAttributesFactoryBean();
regionAttributes.setEvictionAttributes(evictionAttributes);
regionAttributes.setEntryIdleTimeout(entryTti);
regionAttributes.setEntryTimeToLive(entryTtl);
return regionAttributes;
}
#Bean
public EvictionAttributesFactoryBean defaultEvictionAttributes(
#Value("${app.gemfire.region.eviction.action}") String action,
#Value("${app.gemfire.region.eviction.policy-type}") String policyType,
#Value("${app.gemfire.region.eviction.threshold}") int threshold) {
EvictionAttributesFactoryBean evictionAttributes = new EvictionAttributesFactoryBean();
evictionAttributes.setAction(EvictionActionType.valueOfIgnoreCase(action).getEvictionAction());
evictionAttributes.setThreshold(threshold);
evictionAttributes.setType(EvictionPolicyType.valueOfIgnoreCase(policyType));
return evictionAttributes;
}
#Bean
public ExpirationAttributesFactoryBean entryTtiExpirationAttributes(
#Value("${app.gemfire.region.expiration.entry.tti.action}") String action,
#Value("${app.gemfire.region.expiration.entry.tti.timeout}") int timeout) {
ExpirationAttributesFactoryBean expirationAttributes = new ExpirationAttributesFactoryBean();
expirationAttributes.setAction(ExpirationActionType.valueOfIgnoreCase(action).getExpirationAction());
expirationAttributes.setTimeout(timeout);
return expirationAttributes;
}
#Bean
public ExpirationAttributesFactoryBean entryTtlExpirationAttributes(
#Value("${app.gemfire.region.expiration.entry.ttl.action}") String action,
#Value("${app.gemfire.region.expiration.entry.ttl.timeout}") int timeout) {
ExpirationAttributesFactoryBean expirationAttributes = new ExpirationAttributesFactoryBean();
expirationAttributes.setAction(ExpirationActionType.valueOfIgnoreCase(action).getExpirationAction());
expirationAttributes.setTimeout(timeout);
return expirationAttributes;
}
#Bean
public PartitionAttributesFactoryBean defaultPartitionAttributes(
#Value("${app.gemfire.region.partition.local-max-memory}") int localMaxMemory,
#Value("${app.gemfire.region.partition.redundant-copies}") int redundantCopies,
#Value("${app.gemfire.region.partition.total-max-memory}") int totalMaxMemory) {
PartitionAttributesFactoryBean partitionAttributes = new PartitionAttributesFactoryBean();
partitionAttributes.setLocalMaxMemory(localMaxMemory);
partitionAttributes.setRedundantCopies(redundantCopies);
partitionAttributes.setTotalMaxMemory(totalMaxMemory);
return partitionAttributes;
}
#Override
protected SpringApplicationBuilder configure(
SpringApplicationBuilder application) {
return application.sources(applicationClass);
}}
demoService java code:
#Service
public class demoService {
#Autowired
private demoMapper demoMapper;
#Cacheable("demo")
public Fund getDemo(String code) {
Demo demo= demoMapper.getDemo(Code);
return demo;
}
Here is an example of setting entry-ttl among other attributes: https://github.com/spring-projects/spring-gemfire-examples/blob/master/basic/java-config/src/main/java/org/springframework/data/gemfire/example/SpringJavaBasedContainerGemFireConfiguration.java

Spring Redis Error Handle

I am using Spring + Redis as my cache component in the new project. The spring config xml file is:
<!-- Jedis Connection -->
<bean id="jedisConnectionFactory"
class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
p:host-name="${redis.ip}" p:port="${redis.port}" p:use-pool="${redis.use-pool}" />
<!-- Redis Template -->
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
<property name="connectionFactory" ref="jedisConnectionFactory" />
<property name="keySerializer">
<bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />
</property>
<property name="valueSerializer">
<bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />
</property>
</bean>
<bean id="cacheManager" class="org.springframework.data.redis.cache.RedisCacheManager" c:template-ref="redisTemplate"/>
<cache:annotation-driven mode="proxy" proxy-target-class="true" cache-manager="cacheManager" />
The usage is
#Cacheable(value = "cacheManager", key="#userId")
public User getUser(String userId) {
System.out.println("execute==");
return userAdminMapper.getUser(userId);
}
My test case is:
#Test
public void testCacheUser2() {
String id = "test";
User user = userService.getUser(id);
System.out.println(user);
user.setUserCreateDate(new Date());
userService.updateUser(user);
User user2 = userService.getUser(id);
System.out.println(user2);
User user3 = userService.getUser(id);
System.out.println(user3);
}
If the Redis server is running, the code is running correctly. But my question is if I shutdown the Redis server, it will throw the exception:
org.springframework.data.redis.RedisConnectionFailureException: Cannot get Jedis connection; nested exception is redis.clients.jedis.exceptions.JedisConnectionException: java.net.ConnectException: Connection refused: connect
at org.springframework.data.redis.connection.jedis.JedisConnectionFactory.fetchJedisConnector(JedisConnectionFactory.java:140)
at org.springframework.data.redis.connection.jedis.JedisConnectionFactory.getConnection(JedisConnectionFactory.java:229)
at org.springframework.data.redis.connection.jedis.JedisConnectionFactory.getConnection(JedisConnectionFactory.java:57)
at org.springframework.data.redis.core.RedisConnectionUtils.doGetConnection(RedisConnectionUtils.java:128)
at org.springframework.data.redis.core.RedisConnectionUtils.getConnection(RedisConnectionUtils.java:91)
at org.springframework.data.redis.core.RedisConnectionUtils.getConnection(RedisConnectionUtils.java:78)
at org.springframework.data.redis.core.RedisTemplate.execute(RedisTemplate.java:177)
at org.springframework.data.redis.core.RedisTemplate.execute(RedisTemplate.java:152)
at org.springframework.data.redis.cache.RedisCache.get(RedisCache.java:87)
at org.springframework.cache.interceptor.CacheAspectSupport.findInCaches(CacheAspectSupport.java:297)
at org.springframework.cache.interceptor.CacheAspectSupport.findInAnyCaches(CacheAspectSupport.java:287)
at org.springframework.cache.interceptor.CacheAspectSupport.collectPutRequests(CacheAspectSupport.java:266)
at org.springframework.cache.interceptor.CacheAspectSupport.execute(CacheAspectSupport.java:199)
at org.springframework.cache.interceptor.CacheAspectSupport.execute(CacheAspectSupport.java:178)
at org.springframework.cache.interceptor.CacheInterceptor.invoke(CacheInterceptor.java:60)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:644)
at sg.infolab.common.admin.service.impl.UserServiceImpl$$EnhancerBySpringCGLIB$$c7f982a7.getUser(<generated>)
at sg.infolab.admin.test.RedisServiceTest.testCacheUser2(RedisServiceTest.java:35)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:232)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:89)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:175)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: redis.clients.jedis.exceptions.JedisConnectionException: java.net.ConnectException: Connection refused: connect
at redis.clients.jedis.Connection.connect(Connection.java:150)
at redis.clients.jedis.BinaryClient.connect(BinaryClient.java:71)
at redis.clients.jedis.BinaryJedis.connect(BinaryJedis.java:1783)
at org.springframework.data.redis.connection.jedis.JedisConnectionFactory.fetchJedisConnector(JedisConnectionFactory.java:137)
... 50 more
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:351)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:213)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:200)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
at java.net.Socket.connect(Socket.java:529)
at redis.clients.jedis.Connection.connect(Connection.java:144)
... 53 more
I want to ask if the client couldn't connect Redis Server, why will it throw exception? Can we config the scenario like this -- if the cache layer(Redis Server) cannot connect(maybe it is crashed or network is not up), it should directly connect to database and fetch data.
I had the very same problem. I'm developing some data services against a database, using Redis as the cache store by way of Spring Caching annotations. If the Redis server becomes unavailable, I want the services to continue to operate as if uncached, rather than throwing exceptions.
At first I tried a custom CacheErrorHandler, a mechanism provided by Spring. It didn't quite work, because it only handles RuntimeExceptions, and still lets things like java.net.ConnectException blow things up.
In the end what I did is extend RedisTemplate, overriding a few execute() methods so that they log warnings instead of propagating exceptions. It seems like a bit of a hack, and I might have overridden too few execute() methods or too many, but it works like a charm in all my test cases.
There's an important operational aspect to this approach, though. If the Redis server becomes unavailable you must flush it (clean out the entries) before making it available again. Otherwise there's a chance that you might start retrieving cache entries that have incorrect data because of updates that occurred in the meantime.
Below is the source. Feel free to use it. I hope it helps.
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SessionCallback;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.data.redis.serializer.RedisSerializer;
/**
* An extension of RedisTemplate that logs exceptions instead of letting them propagate.
* If the Redis server is unavailable, cache operations are always a "miss" and data is fetched from the database.
*/
public class LoggingRedisTemplate<K, V> extends RedisTemplate<K, V> {
private static final Logger logger = LoggerFactory.getLogger(LoggingRedisTemplate.class);
#Override
public <T> T execute(final RedisCallback<T> action, final boolean exposeConnection, final boolean pipeline) {
try {
return super.execute(action, exposeConnection, pipeline);
}
catch(final Throwable t) {
logger.warn("Error executing cache operation: {}", t.getMessage());
return null;
}
}
#Override
public <T> T execute(final RedisScript<T> script, final List<K> keys, final Object... args) {
try {
return super.execute(script, keys, args);
}
catch(final Throwable t) {
logger.warn("Error executing cache operation: {}", t.getMessage());
return null;
}
}
#Override
public <T> T execute(final RedisScript<T> script, final RedisSerializer<?> argsSerializer, final RedisSerializer<T> resultSerializer, final List<K> keys, final Object... args) {
try {
return super.execute(script, argsSerializer, resultSerializer, keys, args);
}
catch(final Throwable t) {
logger.warn("Error executing cache operation: {}", t.getMessage());
return null;
}
}
#Override
public <T> T execute(final SessionCallback<T> session) {
try {
return super.execute(session);
}
catch(final Throwable t) {
logger.warn("Error executing cache operation: {}", t.getMessage());
return null;
}
}
}
I have added the answer for Spring boot v2 using LettuceConnectionFactory
#Configuration
#EnableCaching
public class RedisCacheConfig extends CachingConfigurerSupport implements CachingConfigurer {
#Value("${redis.hostname:localhost}")
private String redisHost;
#Value("${redis.port:6379}")
private int redisPort;
#Value("${redis.timeout.secs:1}")
private int redisTimeoutInSecs;
#Value("${redis.socket.timeout.secs:1}")
private int redisSocketTimeoutInSecs;
#Value("${redis.ttl.hours:1}")
private int redisDataTTL;
// #Autowired
// private ObjectMapper objectMapper;
#Bean
public LettuceConnectionFactory redisConnectionFactory() {
// LettuceClientConfiguration clientConfig = LettuceClientConfiguration.builder()
// .commandTimeout(Duration.ofSeconds(redisConnectionTimeoutInSecs)).shutdownTimeout(Duration.ZERO).build();
//
// return new LettuceConnectionFactory(new RedisStandaloneConfiguration(redisHost, redisPort), clientConfig);
final SocketOptions socketOptions = SocketOptions.builder().connectTimeout(Duration.ofSeconds(redisSocketTimeoutInSecs)).build();
final ClientOptions clientOptions = ClientOptions.builder().socketOptions(socketOptions).build();
LettuceClientConfiguration clientConfig = LettuceClientConfiguration.builder()
.commandTimeout(Duration.ofSeconds(redisTimeoutInSecs)).clientOptions(clientOptions).build();
RedisStandaloneConfiguration serverConfig = new RedisStandaloneConfiguration(redisHost, redisPort);
final LettuceConnectionFactory lettuceConnectionFactory = new LettuceConnectionFactory(serverConfig, clientConfig);
lettuceConnectionFactory.setValidateConnection(true);
return lettuceConnectionFactory;
}
#Bean
public RedisTemplate<Object, Object> redisTemplate() {
RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<Object, Object>();
redisTemplate.setConnectionFactory(redisConnectionFactory());
return redisTemplate;
}
#Bean
public RedisCacheManager redisCacheManager(LettuceConnectionFactory lettuceConnectionFactory) {
/**
* If we want to use JSON Serialized with own object mapper then use the below config snippet
*/
// RedisCacheConfiguration redisCacheConfiguration =
// RedisCacheConfiguration.defaultCacheConfig().disableCachingNullValues()
// .entryTtl(Duration.ofHours(redisDataTTL)).serializeValuesWith(RedisSerializationContext.SerializationPair
// .fromSerializer(new GenericJackson2JsonRedisSerializer(objectMapper)));
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig().disableCachingNullValues()
.entryTtl(Duration.ofHours(redisDataTTL))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(RedisSerializer.java()));
redisCacheConfiguration.usePrefix();
RedisCacheManager redisCacheManager = RedisCacheManager.RedisCacheManagerBuilder.fromConnectionFactory(lettuceConnectionFactory)
.cacheDefaults(redisCacheConfiguration).build();
redisCacheManager.setTransactionAware(true);
return redisCacheManager;
}
#Override
public CacheErrorHandler errorHandler() {
return new RedisCacheErrorHandler();
}
RedisCacheErrorHandler.java is given below
public class RedisCacheErrorHandler implements CacheErrorHandler {
private static final Logger log = LoggerFactory.getLogger(RedisCacheErrorHandler.class);
#Override
public void handleCacheGetError(RuntimeException exception, Cache cache, Object key) {
handleTimeOutException(exception);
log.info("Unable to get from cache " + cache.getName() + " : " + exception.getMessage());
}
#Override
public void handleCachePutError(RuntimeException exception, Cache cache, Object key, Object value) {
handleTimeOutException(exception);
log.info("Unable to put into cache " + cache.getName() + " : " + exception.getMessage());
}
#Override
public void handleCacheEvictError(RuntimeException exception, Cache cache, Object key) {
handleTimeOutException(exception);
log.info("Unable to evict from cache " + cache.getName() + " : " + exception.getMessage());
}
#Override
public void handleCacheClearError(RuntimeException exception, Cache cache) {
handleTimeOutException(exception);
log.info("Unable to clean cache " + cache.getName() + " : " + exception.getMessage());
}
/**
* We handle redis connection timeout exception , if the exception is handled then it is treated as a cache miss and
* gets the data from actual storage
*
* #param exception
*/
private void handleTimeOutException(RuntimeException exception) {
if (exception instanceof RedisCommandTimeoutException)
return;
}
}
I have the same error. And I managed to solve it by adding two things:
timeout for connectionFactory
error handler
#Configuration
#ConditionalOnProperty(name = "redis.enabled", havingValue = "true")
#EnableCaching
public class RedisCacheConfig extends CachingConfigurerSupport implements CachingConfigurer {
#Value("${redis.host}")
private String host;
#Value("${redis.port}")
private Integer port;
#Value("${redis.expiration.timeout}")
private Integer expirationTimeout;
#Bean
public JedisConnectionFactory redisConnectionFactory() {
JedisConnectionFactory redisConnectionFactory = new JedisConnectionFactory();
redisConnectionFactory.setHostName(host);
redisConnectionFactory.setPort(port);
redisConnectionFactory.setTimeout(10);
return redisConnectionFactory;
}
#Bean
public RedisTemplate<String, Set<String>> redisTemplate(#Autowired RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Set<String>> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
return redisTemplate;
}
#Bean
public CacheManager cacheManager(#Autowired RedisTemplate redisTemplate) {
RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
cacheManager.setDefaultExpiration(expirationTimeout);
return cacheManager;
}
#Override
public CacheErrorHandler errorHandler() {
return new RedisCacheErrorHandler();
}
#Slf4j
public static class RedisCacheErrorHandler implements CacheErrorHandler {
#Override
public void handleCacheGetError(RuntimeException exception, Cache cache, Object key) {
log.info("Unable to get from cache " + cache.getName() + " : " + exception.getMessage());
}
#Override
public void handleCachePutError(RuntimeException exception, Cache cache, Object key, Object value) {
log.info("Unable to put into cache " + cache.getName() + " : " + exception.getMessage());
}
#Override
public void handleCacheEvictError(RuntimeException exception, Cache cache, Object key) {
log.info("Unable to evict from cache " + cache.getName() + " : " + exception.getMessage());
}
#Override
public void handleCacheClearError(RuntimeException exception, Cache cache) {
log.info("Unable to clean cache " + cache.getName() + " : " + exception.getMessage());
}
}
}
LettuceConnectionFactory is not necessary. Just using a custom CacheConfig extends CachingConfigurerSupport. And override the errorHandler() method.
You just need to implement a custom CacheErrorHandler, like #Tan mally do in his answer.
You can use CacheErrorHandler as suggested in other answers. But you should make sure to make
RedisCacheManager transactionAware to false in your Redis Cache Config(to make sure the transaction is committed early when executing the caching part and the error is caught by CacheErrorHandler and don't wait until the end of the execution which skips CacheErrorHandler part). The function to set transactionAware to false looks like this:
#Bean
public RedisCacheManager redisCacheManager(LettuceConnectionFactory lettuceConnectionFactory) {
JdkSerializationRedisSerializer redisSerializer = new JdkSerializationRedisSerializer(getClass().getClassLoader());
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofHours(redisDataTTL))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer));
redisCacheConfiguration.usePrefix();
RedisCacheManager redisCacheManager = RedisCacheManager.RedisCacheManagerBuilder.fromConnectionFactory(lettuceConnectionFactory)
.cacheDefaults(redisCacheConfiguration)
.build();
redisCacheManager.setTransactionAware(false);
return redisCacheManager;
}