Git Product home page Git Product logo

hibernate-redis's Introduction

hibernate-redis

Maven Central Build Status

hibernate (4.x, 5.1.x, 5.2.x) 2nd level cache provider using redis server 3.x. with Redisson 2.3.x

Reduce cache size by Redisson SnappyCodec (see snappy-java, Fast-Serialization)

Note

From 2.2.1 onwards Hibernate region naming (hibernate.cache.region_prefix) has been simplified to "hibernate".

hibernate-core 5.2.x based on Java 8, use hibernate-redis 2.2.0 or higher

Region factory for hibernate 5.2.x is hibernate.redis.cache.hibernate52.SingletonRedisRegionFactory

Setup

Maven Repository

add dependency

<dependency>
    <groupId>com.github.debop</groupId>
    <artifactId>hibernate-redis</artifactId>
    <version>2.3.2</version>
</dependency>

Optional dependencies. Redisson support various codec (serializer, compression). you can choose other codec. see Redisson Help.

<dependency>
    <groupId>org.redisson</groupId>
    <artifactId>redisson</artifactId>
    <version>${redisson.version}</version>
</dependency>
<dependency>
    <groupId>de.ruedigermoeller</groupId>
    <artifactId>fst</artifactId>
    <version>${fst.version}</version>
</dependency>
<dependency>
    <groupId>org.xerial.snappy</groupId>
    <artifactId>snappy-java</artifactId>
    <version>${snappy-java.version}</version>
</dependency>
Setup hibernate configuration

Setup hibernate configuration (Note package name for hibernate 4 / hibernate 5 / hibernate52)

// Secondary Cache
props.put(Environment.USE_SECOND_LEVEL_CACHE, true);
props.put(Environment.USE_QUERY_CACHE, true);
props.put(Environment.CACHE_REGION_FACTORY, org.hibernate.cache.redis.hibernate52.SingletonRedisRegionFactory.class.getName());
props.put(Environment.CACHE_REGION_PREFIX, "hibernate");

// Optional setting for second level cache statistics
props.setProperty(Environment.GENERATE_STATISTICS, "true");
props.setProperty(Environment.USE_STRUCTURED_CACHE, "true");

// Hibernate 4
props.setProperty(Environment.TRANSACTION_STRATEGY, JdbcTransactionFactory.class.getName());

// Configuration for Redis that used by hibernate
props.put(Environment.CACHE_PROVIDER_CONFIG, "hibernate-redis.properties");

also same configuration for using Spring Framework or Spring Data JPA

Redis settings for hibernate-redis

sample for hibernate-redis.properties

 ##########################################################
 #
 # properities for hibernate-redis
 #
 ##########################################################

 # Redisson configuration file
 redisson-config=conf/redisson.yaml

 # Cache Expiry settings
 # 'hibernate' is second cache prefix
 # 'common', 'account' is actual region name
 redis.expiryInSeconds.default=120
 redis.expiryInSeconds.hibernate.common=0
 redis.expiryInSeconds.hibernate.account=1200

sample for Redisson configuration (see more samples )

# redisson configuration for redis servers
# see : https://github.com/mrniko/redisson/wiki/2.-Configuration

singleServerConfig:
  idleConnectionTimeout: 10000
  pingTimeout: 1000
  connectTimeout: 1000
  timeout: 1000
  retryAttempts: 1
  retryInterval: 1000
  reconnectionTimeout: 3000
  failedAttempts: 1
  password: null
  subscriptionsPerConnection: 5
  clientName: null
  address: "redis://127.0.0.1:6379"
  subscriptionConnectionMinimumIdleSize: 1
  subscriptionConnectionPoolSize: 25
  connectionMinimumIdleSize: 5
  connectionPoolSize: 100
  database: 0
  dnsMonitoring: false
  dnsMonitoringInterval: 5000
threads: 0
# Codec
codec: !<org.redisson.codec.SnappyCodec> {}
useLinuxNativeEpoll: false
eventLoopGroup: null

Hibernate configuration via Spring Application property files

In Spring applications, the hibernate- and hibernate-redis configuration represented above can be configured within Spring application property files like below.

spring.jpa.properties.hibernate.cache.use_second_level_cache=true
spring.jpa.properties.hibernate.cache.use_query_cache=true
spring.jpa.properties.hibernate.cache.region.factory_class=org.hibernate.cache.redis.hibernate52.SingletonRedisRegionFactory
spring.jpa.properties.hibernate.cache.region_prefix=hibernate

spring.jpa.properties.hibernate.cache.use_structured_entries=true
spring.jpa.properties.hibernate.generate_statistics=true

spring.jpa.properties.redisson-config=classpath:conf/redisson.yaml

spring.jpa.properties.redis.expiryInSeconds.default=120
spring.jpa.properties.redis.expiryInSeconds.hibernate.common=0
spring.jpa.properties.redis.expiryInSeconds.hibernate.account=1200

Setup hibernate entity to use cache

add @org.hibernate.annotations.Cache annotation to Entity class like this

@Entity
@Cache(region="common", usage = CacheConcurrencyStrategy.READ_WRITE)  // or @Cacheable(true) for JPA
@Getter
@Setter
public class Item implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    private String description;

    private static final long serialVersionUID = -281066218676472922L;
}

How to monitor hibernate-cache is running

run "redis-cli monitor" command in terminal. you can see putting cached items, retrieving cached items.

Sample code

see hibernate-examples module

hibernate-redis's People

Contributors

apotapov avatar debop avatar gebeater avatar johnou avatar jontejj avatar stadia avatar theaquarium avatar ti3r avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

hibernate-redis's Issues

Deploy source and javadoc to Bintray

Artifacts are deployed to Bintray but as of yet, only binary artifacts are deployed. To ease debugging, it should be useful to deploy also source and Javadoc artifacts

Add hibernate-redis to Maven Central

First, thanks for the work you've put into this great project!

If I understand the README correctly, it seems that you aren't sure how to add this project to the Maven Central repository. I would like to help get this into the central repository if that is possible.

If this is not a task you're interested in undertaking, I would be happy to make some of the minor changes needed and create pull requests, or do the full process myself.

Metadata

groupId

The group ID must be unique to the project and controlled by the maintainer. In the case of this project, com.github.debop would make the most sense.

artifactId

The artifactId, hibernate-redis will work as it currently is.

version

1.5.5 seems like the current version.

Package Signing

The important bits here are that you must sign your artifacts and the key must be available through a public PGP key server. Relevant information on how to do this is located here: https://docs.sonatype.org/display/Repository/How+To+Generate+PGP+Signatures+With+Maven

Distribution to Repository

The easiest way to get this up would likely be to use the Sonatype OSS repository doing a manual upload. Since this seems to be a fairly low-frequency project, that should be an OK way to get started. (See https://docs.sonatype.org/display/Repository/Uploading+3rd-party+Artifacts+to+The+Central+Repository)

Cache Expiry 기능 추가

Redis 의 Expire 값을 모든 Region에 적용한다.
Expiry 설정 정보를 지정하는 것도 넣는다.

Hibernate-redis and Amazon Elasticache

Hi,

I'm working with hibernate-redis project.
I've a MySQL database with all entities marked with this annotations:

@Cacheable
@Cache(usage=CacheConcurrencyStrategy.READ_WRITE, region="MyEntity")

and for each @OneToMany relationships, I've:
@Cache(usage=CacheConcurrencyStrategy.READ_WRITE, region="MyEntity.MyEntity2")

In my hibernate-redis.properties I've set these fields:

redis.host=myamazonhost
redis.port=6379
redis.database=1
redis.expiryInSeconds=120
redis.expiryInSeconds.hibernate.common=0
redis.expiryInSeconds.hibernate.account=1200

and in my hibernate config:

Map<String, String> props = new HashMap<String, String>(configuration.getDatabaseConfiguration().getProperties());
props.put(org.hibernate.cfg.Environment.USE_SECOND_LEVEL_CACHE, "true");
props.put(org.hibernate.cfg.Environment.USE_QUERY_CACHE, "true");
props.put(org.hibernate.cfg.Environment.GENERATE_STATISTICS, "true");               
props.put(org.hibernate.cfg.Environment.CACHE_REGION_FACTORY,SingletonRedisRegionFactory.class.getName());
props.put(org.hibernate.cfg.Environment.CACHE_REGION_PREFIX, "hibernate:");
props.put(org.hibernate.cfg.Environment.GENERATE_STATISTICS, "true");
props.put(org.hibernate.cfg.Environment.USE_STRUCTURED_CACHE, "true");
props.put(org.hibernate.cfg.Environment.TRANSACTION_STRATEGY, JdbcTransactionFactory.class.getName());

.....with no connection problems.

But, when I query the MyEntity table, in my redis-cli monitor I've:

"hset" "hibernate:.MyEntity" "com.myproject.MyEntity#14" "\xac\xed\x00.................... etc"

so I think that the entry was added to cache.
But when I execute the command KEYS * into redis shell, I've only:

  1. "ElastiCacheMasterReplicationTimestamp"

Why? Where I wrong?

Release it on central

Hi,

do you think you are able to release your project on maven central or bintray? Would be great! :)

It's a great project!

Thanks
Conny

Support to another strategy of cache expiration.

Maybe this library can support another type of expiration strategy:

Today:
Daemon cleaning Thread.
Z scored set put on user put.
Z verification ou user get.

Proposal:
Store values with 8 bytes long prefix (expiration date) metadata.
When user gets value, verify expiration metadata first.
If expired, return null and send a delete command in background, if not return object.
Define expiration of Hash to redis using command EXPIRE every time then a user put values to region
Redis will clean entire Hash if anybody put new values (daybreak)

The idea is mantain both, and let user choose.

Does hibernate-redis work with cglib?

Hi!

I'm getting a deserialize warning when trying to access a lazily instantiated reference. Do you know if this library supports CGLIB and if so Is there anything special I need to do to support lazy references?

Thank You
Eric

12:53:40:309 WARN redis.serializer.FstRedisSerializer:62 - Fail to deserialize bytes.
java.io.IOException: java.lang.RuntimeException: java.io.StreamCorruptedException: Unknown serialized type
at de.ruedigermoeller.serialization.FSTObjectInput.readObject(FSTObjectInput.java:168)
at org.hibernate.cache.redis.serializer.FstRedisSerializer.deserialize(FstRedisSerializer.java:60)
at org.hibernate.cache.redis.serializer.SnappyRedisSerializer.deserialize(SnappyRedisSerializer.java:41)
at org.hibernate.cache.redis.jedis.JedisClient.deserializeValue(JedisClient.java:502)
at org.hibernate.cache.redis.jedis.JedisClient.get(JedisClient.java:179)
at org.hibernate.cache.redis.regions.RedisTransactionalDataRegion.get(RedisTransactionalDataRegion.java:75)
at org.hibernate.cache.redis.strategy.NonStrictReadWriteRedisEntityRegionAccessStrategy.get(NonStrictReadWriteRedisEntityRegionAccessStrategy.java:48)
at org.hibernate.engine.internal.CacheHelper.fromSharedCache(CacheHelper.java:55)
at org.hibernate.engine.internal.CacheHelper.fromSharedCache(CacheHelper.java:67)
at org.hibernate.event.internal.DefaultLoadEventListener.loadFromSecondLevelCache(DefaultLoadEventListener.java:598)
at org.hibernate.event.internal.DefaultLoadEventListener.doLoad(DefaultLoadEventListener.java:452)
at org.hibernate.event.internal.DefaultLoadEventListener.load(DefaultLoadEventListener.java:213)
at org.hibernate.event.internal.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:146)
at org.hibernate.internal.SessionImpl.fireLoad(SessionImpl.java:1106)
at org.hibernate.internal.SessionImpl.immediateLoad(SessionImpl.java:1012)
at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:174)
at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:286)
at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:185)
at com.compay.domain.portfolio.Asset_$$jvst5c6_44.hashCode(Asset$$_jvst5c6_44.java)

에러 상황에서 로그가 너무 많이 떨어집니다

runWithTx 와 run 메소드에서 에러가 발생할 경우 로그가 너무 많이 떨어집니다.

ERROR 2013-08-28 12:45:45 ip-10-132-194-166 [http-bio-8080-exec-205] o.h.cache.redis.jedis.JedisClient:433 - Redis 작업 중 예외가 발생했습니다.
redis.clients.jedis.exceptions.JedisDataException: EXECABORT Transaction discarded because of previous errors.
at redis.clients.jedis.Protocol.processError(Protocol.java:59) ~[jedis-2.1.0.jar:na]
at redis.clients.jedis.Protocol.process(Protocol.java:66) ~[jedis-2.1.0.jar:na]
at redis.clients.jedis.Protocol.read(Protocol.java:131) ~[jedis-2.1.0.jar:na]
at redis.clients.jedis.Connection.getObjectMultiBulkReply(Connection.java:206) ~[jedis-2.1.0.jar:na]
at redis.clients.jedis.BinaryTransaction.exec(BinaryTransaction.java:28) ~[jedis-2.1.0.jar:na]
at org.hibernate.cache.redis.jedis.JedisClient.runWithTx(JedisClient.java:431) [hibernate3-redis-1.0.2.jar:na]

Serialization issue when tomcat reload

Hello,

Thanks for your work.

Thanks to issu #19, I can set my classloader to the conf with:
FstRedisSerializer.getConf().setClassLoader(Thread.currentThread().getContextClassLoader());

Everything works fine when my application starts. When the application reloads I have this stacktrace:

org.hibernate.PropertyAccessException: could not set a field value by reflection setter of com.myPackage.MyEnum

Caused by: java.lang.IllegalArgumentException: Can not set com.myPackage.MyEnum
field com.MyEntity.enumAttribute to com.myPackage.MyEnum

It seems FST keeps lots of things in cache but currently we can't clear it, could you give a method to clear cached configuration

Provide the ability to read Redis-specific properties from an external source

Currently, JedisTool relies on a private static method called "loadCacheProperties" to read redis-specific property values. It will attempt to read from a file, which is either on the file system, or in the classpath.

This type of implementation is shortsighted, as it doesn't give the user the ability to read the values from an external data source (such as a distributed key/value system, i.e. etcd).

It would be nice to provide the ability to override this functionality.

Allow JedisTool cacheProps to be set without going through the JedisTool

The indirection of the DataRegions calling static methods to get their expiration times requires all you to go through the JedisTool to create a JedisClient etc. This is awkward in many situations in particular for plugins such as the Grails wrapper that is currently bypassing that configuration altogether (and hence not getting configuration per cache region:

https://github.com/Alotor/grails-redis-hibernate-cache/blob/master/src/java/org/hibernate/cache/redis/GrailsRedisRegionFactory.java

It would be better if the RegionFactory stored all its properties and cacheProps in the parent class and then had the various DataRegions read their expiry key from that list of properties.

That would would allow consumers to create RegionFactories in more flexible ways in particular to supply the expiration properties in the original properties rather than being forced to use a external file and set Environment.CACHE_PROVIDER_CONFIG. (which is very much not the configuration style of Grails plugins etc. etc.)

Question: missing hibernate-redis-client jar?

Hi,
I'm trying to use the 2.0.2 release and have added the maven dependencies as explained in the readme but maven is complaining that Could not find artifact com.github.debop:hibernate-redis-client:jar:2.0.2

This is what I added in my pom.xml

<dependency>
    <groupId>com.github.debop</groupId>
    <artifactId>hibernate-redis</artifactId>
    <version>2.0.2</version>
</dependency>

I've also added the jcenter repository into my pom and am able to see the other jars. When I browse to the jcenter repo, I can see the hibernate-redis and hibernate-redis-parent artifacts, but no hibernate-redis-client artifact. Am I missing something?

Test problems

Hello, I'm using this class of JpaRepositoryTest.java for testing:

@slf4j
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { JpaMySqlConfiguration.class })
public abstract class AbstractJpaTest {

I've changed it, and I have successfully initialized the database.

When I use employeeFindByEmpNo

@test
public void employeeFindByEmpNo() {
Employee emp = new Employee();
emp.setName("Sunghyouk Bae");
emp.setEmpNo("21011");
emp = empRepository.saveAndFlush(emp);
em.clear();

    Employee loaded = empRepository.findByEmpNo(emp.getEmpNo());
    assertThat(loaded).isNotNull();
    assertThat(loaded).isEqualTo(emp);
    assertThat(loaded.getUpdatedTimestamp()).isNotNull();
    log.debug("Employee=[{}]", loaded);
}

the method of repeatedly testing and processing to

empRepository.findByEmpNo (emp.getEmpNo ())

, it always sending SQL statements to the database query, and not from the redis read, this is why?

Maven repository issues

Hi,

I'm trying to use Nexus to use http://dl.bintray.com/debop/maven/ to pull in 2.0.2 as a runtime dependency with gradle but its having problems. I'm not very familiar with how maven is setup but it lists hibernate-redis-client, hibernate-redis-hibernate4 and hibernate-redis-hibernate5 as compile time dependencies however it cant find these in any repo. Have I misconfigured Nexus or do these need to be added? Happy to help in any way I can.

change Java Built In Serializer to Fast-Serializer

I test some serializer for reduce cache size and increse speed serialization.

try message pack, google proto-buff, Kryo, Fast-Serialization ...

Message Pack need @message annotation (if you want not to use, register type)
proto-buff, Kryo does not match for JPA
but Fast-Serialization is fast and simple, thread-safe!

I make some benchmark ...

warn-up : 37098
binary-small : 59590
binary-long : 343960

warn-up : 40268
snappy-small : 22590
snappy-long : 79545

warn-up : 227796
FST-small : 18828
FST-long : 259602

warn-up : 516
FST-Snappy-small : 9312
FST-Snappy-long : 21542

I decide to use FST + Snappy !

It's so fast, I guess!

deleteRegion 에서 NullPointerException 이 발생합니다

JedisClient 클래스의 deleteRegion 에서 널포인트 에러가 떨어집니다.

keySet을 가져오기 위한 run 메소드에서 redis와 연결에 문제가 있어서 null을 리턴하고
keySet.size()을 호출해서 나는 것 같습니다.

Caused by: org.hibernate.cache.CacheException: java.lang.NullPointerException
at org.hibernate.cache.redis.jedis.JedisClient.deleteRegion(JedisClient.java:324) ~[hibernate3-redis-1.2.0.jar:na]
at org.hibernate.cache.redis.regions.RedisTransactionalDataRegion.clear(RedisTransactionalDataRegion.java:92) ~[hibernate3-redis-1.2.0.jar:na]
at org.hibernate.cache.redis.strategy.AbstractRedisAccessStrategy.removeAll(AbstractRedisAccessStrategy.java:85) ~[hibernate3-redis-1.2.0.jar:na]
at org.hibernate.action.BulkOperationCleanupAction$EntityCleanup.(BulkOperationCleanupAction.java:206) ~[hibernate-core-3.6.10.Final.jar:3.6.10.Final]

Serialization doesn't support LocalDateTime from Java 8 (java.time)

Here is the stack trace:

2015-07-06 17:46:32.734  WARN 64242 --- [io-12345-exec-2] o.h.c.r.serializer.FstRedisSerializer    : Fail to deserialize bytes.

java.io.IOException: java.lang.RuntimeException: java.io.StreamCorruptedException: Unknown serialized type
    at de.ruedigermoeller.serialization.FSTObjectInput.readObject(FSTObjectInput.java:168)
    at org.hibernate.cache.redis.serializer.FstRedisSerializer.deserialize(FstRedisSerializer.java:60)
    at org.hibernate.cache.redis.serializer.SnappyRedisSerializer.deserialize(SnappyRedisSerializer.java:41)
    at org.hibernate.cache.redis.jedis.JedisClient.deserializeValue(JedisClient.java:502)
    at org.hibernate.cache.redis.jedis.JedisClient.get(JedisClient.java:179)
    at org.hibernate.cache.redis.regions.RedisTransactionalDataRegion.get(RedisTransactionalDataRegion.java:75)
    at org.hibernate.cache.redis.strategy.TransactionalRedisEntityRegionAccessStrategy.get(TransactionalRedisEntityRegionAccessStrategy.java:55)
    at org.hibernate.engine.internal.CacheHelper.fromSharedCache(CacheHelper.java:55)
    at org.hibernate.engine.internal.CacheHelper.fromSharedCache(CacheHelper.java:67)
    at org.hibernate.event.internal.DefaultLoadEventListener.loadFromSecondLevelCache(DefaultLoadEventListener.java:597)
    at org.hibernate.event.internal.DefaultLoadEventListener.doLoad(DefaultLoadEventListener.java:451)
    at org.hibernate.event.internal.DefaultLoadEventListener.load(DefaultLoadEventListener.java:212)
    at org.hibernate.event.internal.DefaultLoadEventListener.proxyOrLoad(DefaultLoadEventListener.java:274)
    at org.hibernate.event.internal.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:150)
    at org.hibernate.internal.SessionImpl.fireLoad(SessionImpl.java:1070)
    at org.hibernate.internal.SessionImpl.access$2000(SessionImpl.java:176)
    at org.hibernate.internal.SessionImpl$IdentifierLoadAccessImpl.load(SessionImpl.java:2551)
    at org.hibernate.internal.SessionImpl.get(SessionImpl.java:955)
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.find(AbstractEntityManagerImpl.java:1110)
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.find(AbstractEntityManagerImpl.java:1074)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:344)
    at com.sun.proxy.$Proxy71.find(Unknown Source)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:291)
    at com.sun.proxy.$Proxy71.find(Unknown Source)
    at org.springframework.data.jpa.repository.support.SimpleJpaRepository.findOne(SimpleJpaRepository.java:237)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.executeMethodOn(RepositoryFactorySupport.java:436)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:421)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:393)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$DefaultMethodInvokingMethodInterceptor.invoke(RepositoryFactorySupport.java:506)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodIntercceptor.invoke(CrudMethodMetadataPostProcessor.java:122)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
    at com.sun.proxy.$Proxy73.findOne(Unknown Source)
    at org.springframework.data.repository.CrudRepository$findOne.call(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:45)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:110)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:122)
    at com.tliu3.demo.service.UserService.update(UserService.groovy:39)
    at com.tliu3.demo.service.UserService$$FastClassBySpringCGLIB$$2474e212.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:717)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:653)
    at com.tliu3.demo.service.UserService$$EnhancerBySpringCGLIB$$a16f5425.update(<generated>)
    at com.tliu3.demo.service.UserService$update$0.call(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:45)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:110)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:130)
    at com.tliu3.demo.controllers.UserController.update(UserController.groovy:50)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:776)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:705)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:967)
    at org.springframework.web.servlet.FrameworkServlet.doPut(FrameworkServlet.java:880)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:651)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:843)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.springframework.boot.actuate.autoconfigure.EndpointWebMvcAutoConfiguration$ApplicationContextHeaderFilter.doFilterInternal(EndpointWebMvcAutoConfiguration.java:295)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.springframework.boot.actuate.trace.WebRequestTraceFilter.doFilterInternal(WebRequestTraceFilter.java:102)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:85)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.springframework.boot.actuate.autoconfigure.MetricsFilter.doFilterInternal(MetricsFilter.java:68)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:668)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1521)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1478)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.RuntimeException: java.io.StreamCorruptedException: Unknown serialized type
    at de.ruedigermoeller.serialization.util.FSTUtil.rethrow(FSTUtil.java:119)
    at de.ruedigermoeller.serialization.FSTObjectInput.readObjectWithHeader(FSTObjectInput.java:265)
    at de.ruedigermoeller.serialization.FSTObjectInput.readArray(FSTObjectInput.java:831)
    at de.ruedigermoeller.serialization.FSTObjectInput.instantiateArray(FSTObjectInput.java:326)
    at de.ruedigermoeller.serialization.FSTObjectInput.instantiateSpecialTag(FSTObjectInput.java:288)
    at de.ruedigermoeller.serialization.FSTObjectInput.readObjectWithHeader(FSTObjectInput.java:255)
    at de.ruedigermoeller.serialization.FSTObjectInput.readObjectFields(FSTObjectInput.java:537)
    at de.ruedigermoeller.serialization.FSTObjectInput.instantiateAndReadNoSer(FSTObjectInput.java:403)
    at de.ruedigermoeller.serialization.FSTObjectInput.readObjectWithHeader(FSTObjectInput.java:262)
    at de.ruedigermoeller.serialization.FSTObjectInput.readObjectInternal(FSTObjectInput.java:230)
    at de.ruedigermoeller.serialization.FSTObjectInput.readObject(FSTObjectInput.java:210)
    at de.ruedigermoeller.serialization.FSTObjectInput.readObject(FSTObjectInput.java:165)
    ... 131 common frames omitted
Caused by: java.io.StreamCorruptedException: Unknown serialized type
    at java.time.Ser.readInternal(Ser.java:271)
    at java.time.Ser.readExternal(Ser.java:246)
    at de.ruedigermoeller.serialization.FSTObjectInput.instantiateAndReadNoSer(FSTObjectInput.java:393)
    at de.ruedigermoeller.serialization.FSTObjectInput.readObjectWithHeader(FSTObjectInput.java:262)
    ... 141 common frames omitted

The "unknown serialized type" value is 66, which is unknown to the java.time.Ser class. Valid range is 1..14.

Here are my entities:
BaseEntity:

package com.tliu3.demo.db.model

import java.time.LocalDateTime
import javax.persistence.Column
import javax.persistence.GeneratedValue
import javax.persistence.GenerationType
import javax.persistence.Id
import javax.persistence.MappedSuperclass
import javax.persistence.PrePersist
import javax.persistence.PreUpdate
import javax.persistence.Version

import org.hibernate.annotations.Type

import groovy.transform.ToString

@MappedSuperclass
@ToString(includeNames = true, includePackage = false, excludes = [])
public class BaseEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    Long id

    @Version
    Long version

    @Type(type = "org.jadira.usertype.dateandtime.threeten.PersistentLocalDateTime")
    @Column(name = "create_date", updatable = false, nullable = false)
    LocalDateTime createDate;

    @Type(type = "org.jadira.usertype.dateandtime.threeten.PersistentLocalDateTime")
    @Column(name = "update_date", updatable = false, nullable = false)
    LocalDateTime updateDate;

    @PrePersist
    @PreUpdate
    private void updateTimestamps() {
        updateDate = LocalDateTime.now()
        if (createDate == null) {
            createDate = LocalDateTime.now()
        }
    }
}

User Entity:

package com.tliu3.demo.db.model

import javax.persistence.Entity
import javax.persistence.Table

import org.hibernate.annotations.Cache
import org.hibernate.annotations.CacheConcurrencyStrategy

import groovy.transform.ToString

@Entity
@Table(name = "user")
@ToString(includePackage = false, includeNames = true, includeSuper = true)
@Cache(region = "common", usage = CacheConcurrencyStrategy.TRANSACTIONAL)
public class User extends BaseEntity {
    String name

    String sex

    Long age
}

I configed redis as my hibernate's second cache, But I can't see any items in my redis.

1.My code to operate hibernate:
SessionFactory sessionFactory = new OracleUtils().createHibernateSessionFactory("hibernate.cfg.xml");
sessionFactory.getStatistics().setStatisticsEnabled(true);
sessionFactory.getStatistics().clear();
Session session = sessionFactory.openSession();
session.beginTransaction();
Emp emp = new Emp((int)Math.floor(Math.random()*100 + 1));
session.save(emp);
session.getTransaction().commit();
session.close();

2.My hibernate config:seems the tag "<" is not showing correctly, So I copy it as the following:

     hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver
     hibernate.connection.password">sgbiz
     hibernate.connection.url">jdbc:oracle:thin:@10.6.0.46:1521:dlsc
     hibernate.connection.username">sgbiz
     hibernate.default_schema">SGBIZ
     hibernate.dialect">org.hibernate.dialect.Oracle10gDialect
     show_sql">true
     hibernate.cache.use_second_level_cache">true
     hibernate.cache.use_query_cache">true
     hibernate.cache.region.factory_class">org.hibernate.cache.redis.SingletonRedisRegionFactory
     mapping class="com.epri.dlsc.oracle.entities.Emp"

3.My hibernate-redis.properties:

Redis Server for hibernate 2nd cache

redis.host=10.6.0.45
redis.port=6379

redis.timeout=2000
redis.password=123456

database for hibernate cache

redis.database=0

redis.database=1

hiberante 2nd cache default expiry (seconds)

redis.expiryInSeconds=120

expiry of hibernate.common region (seconds) // hibernate is prefix, region name is common

redis.expiryInSeconds.hibernate.common=0

expiry of hibernate.account region (seconds) // hibernate is prefix, region name is account

redis.expiryInSeconds.hibernate.account=1200

4.My Emp entity:
/**

  • Emp generated by hbm2java
    */
    @entity
    @table(name = "EMP")
    @Cache(region="common", usage = CacheConcurrencyStrategy.READ_WRITE)
    public class Emp implements java.io.Serializable {

    private int empno;
    private String ename;
    private String job;
    private BigDecimal salary;
    ........

Can you give me any suggestions?

Destroy JedisPool on RedisRegionFactory.stop()

Today, code is only setting redis(JedisClient) instance to null.

This cause some problems when undeploy a application in a JEE server,
because classloader was done.

Just call destroy before clean redis instance:

redis.getJedisPool().destroy();
redis = null;

Access to FSTConfiguration in FstRedisSerializer

First off, thanks for a great library! I'm looking forward to integrating it into my project. But I hit a bit of roadblock at the moment.

TL:DR; Please provide access to FSTConfiguration file that's instantiated inside of FstRedisSerializer.

I'm using Java Play framework (http://www.playframework.com/) as an application container for my app. It uses its own ClassLoaders to provide on the fly recompilation.

This causes issues when FST tries to deserialize objects using Class.forName. FSTConfiguration provides a method for setting a different ClassLoader. Unfortunately, it's not easy to get to because it's instantiated as private static final in FSTRedisSerializer.

This is only an issue in dev environment. In production, Play uses standard ClassLoaders, so everything works great. But this makes testing and debugging much more difficult.

Thanks.

Enum serilization issue

I have the following enum that serves as a field on a hibernate entity:

package com.bvg.models.enums;

public enum Gender {
    MALE,
    FEMALE
}

Entity:

@Entity
@Table(name = "users")
@Getter
@Setter
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class User extends AbstractModel implements Subject {
...
@Enumerated(EnumType.STRING)
    @Column
    protected Gender gender;
...
}

I have configured hibernate-redis as per instructions, and things seem to work fine for entities that use primitive types for fields (String, int, boolean, etc) However, this enum is giving me trouble. Do I need to register it with the serializer somehow? Seems like it should be able to handle an enum.

Here's the stack trace that i get:

22:48:59.295 [application-akka.actor.default-dispatcher-9] WARN  o.h.c.r.s.FstRedisSerializer.deserialize 53 - Fail to deserialize bytes.
java.io.IOException: java.lang.RuntimeException: CLASSNAME:com.bvg.models.enums.Gender
    at de.ruedigermoeller.serialization.FSTObjectInput.readObject(FSTObjectInput.java:168) ~[fst-1.53.jar:na]
    at org.hibernate.cache.redis.serializer.FstRedisSerializer.deserialize(FstRedisSerializer.java:51) ~[hibernate-redis-1.5.10.jar:na]
    at org.hibernate.cache.redis.serializer.SnappyRedisSerializer.deserialize(SnappyRedisSerializer.java:41) [hibernate-redis-1.5.10.jar:na]
    at org.hibernate.cache.redis.jedis.JedisClient.deserializeValue(JedisClient.java:475) [hibernate-redis-1.5.10.jar:na]
    at org.hibernate.cache.redis.jedis.JedisClient.get(JedisClient.java:165) [hibernate-redis-1.5.10.jar:na]
    at org.hibernate.cache.redis.regions.RedisTransactionalDataRegion.get(RedisTransactionalDataRegion.java:75) [hibernate-redis-1.5.10.jar:na]
    at org.hibernate.cache.redis.strategy.AbstractReadWriteRedisAccessStrategy.get(AbstractReadWriteRedisAccessStrategy.java:52) [hibernate-redis-1.5.10.jar:na]
    at org.hibernate.engine.internal.CacheHelper.fromSharedCache(CacheHelper.java:55) [hibernate-core-4.3.4.Final.jar:4.3.4.Final]
    at org.hibernate.engine.internal.CacheHelper.fromSharedCache(CacheHelper.java:67) [hibernate-core-4.3.4.Final.jar:4.3.4.Final]
    at org.hibernate.event.internal.DefaultLoadEventListener.loadFromSecondLevelCache(DefaultLoadEventListener.java:597) [hibernate-core-4.3.4.Final.jar:4.3.4.Final]
    at org.hibernate.event.internal.DefaultLoadEventListener.doLoad(DefaultLoadEventListener.java:451) [hibernate-core-4.3.4.Final.jar:4.3.4.Final]
    at org.hibernate.event.internal.DefaultLoadEventListener.load(DefaultLoadEventListener.java:212) [hibernate-core-4.3.4.Final.jar:4.3.4.Final]
    at org.hibernate.event.internal.DefaultLoadEventListener.proxyOrLoad(DefaultLoadEventListener.java:274) [hibernate-core-4.3.4.Final.jar:4.3.4.Final]
    at org.hibernate.event.internal.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:150) [hibernate-core-4.3.4.Final.jar:4.3.4.Final]
    at org.hibernate.internal.SessionImpl.fireLoad(SessionImpl.java:1070) [hibernate-core-4.3.4.Final.jar:4.3.4.Final]
    at org.hibernate.internal.SessionImpl.access$2000(SessionImpl.java:176) [hibernate-core-4.3.4.Final.jar:4.3.4.Final]
    at org.hibernate.internal.SessionImpl$IdentifierLoadAccessImpl.load(SessionImpl.java:2551) [hibernate-core-4.3.4.Final.jar:4.3.4.Final]
    at org.hibernate.internal.SessionImpl.get(SessionImpl.java:955) [hibernate-core-4.3.4.Final.jar:4.3.4.Final]
    at com.bvg.models.daos.DaoImpl.get(DaoImpl.java:78) [classes/:na]
    at com.bvg.models.daos.DaoImpl.getWithRetry(DaoImpl.java:83) [classes/:na]
    at com.bvg.actors.DbBasedActor.execute(DbBasedActor.java:52) [classes/:na]
    at com.bvg.actors.DbBasedActor.execute(DbBasedActor.java:16) [classes/:na]
    at com.bvg.models.session.HibernateSessionHelper.executeTransactionally(HibernateSessionHelper.java:82) [classes/:na]
    at com.bvg.actors.DbBasedActor.onReceive(DbBasedActor.java:37) [classes/:na]
    at akka.actor.UntypedActor$$anonfun$receive$1.applyOrElse(UntypedActor.scala:167) [akka-actor_2.10.jar:2.2.0]
    at akka.actor.ActorCell.receiveMessage(ActorCell.scala:498) [akka-actor_2.10.jar:2.2.0]
    at akka.actor.ActorCell.invoke(ActorCell.scala:456) [akka-actor_2.10.jar:2.2.0]
    at akka.dispatch.Mailbox.processMailbox(Mailbox.scala:237) [akka-actor_2.10.jar:2.2.0]
    at akka.dispatch.Mailbox.run(Mailbox.scala:219) [akka-actor_2.10.jar:2.2.0]
    at akka.dispatch.ForkJoinExecutorConfigurator$AkkaForkJoinTask.exec(AbstractDispatcher.scala:386) [akka-actor_2.10.jar:2.2.0]
    at scala.concurrent.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:260) [scala-library.jar:na]
    at scala.concurrent.forkjoin.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1339) [scala-library.jar:na]
    at scala.concurrent.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1979) [scala-library.jar:na]
    at scala.concurrent.forkjoin.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:107) [scala-library.jar:na]
Caused by: java.lang.RuntimeException: CLASSNAME:com.bvg.models.enums.Gender
    at de.ruedigermoeller.serialization.FSTClazzNameRegistry.classForName(FSTClazzNameRegistry.java:198) ~[fst-1.53.jar:na]
    at de.ruedigermoeller.serialization.FSTClazzNameRegistry.classForName(FSTClazzNameRegistry.java:178) ~[fst-1.53.jar:na]
    at de.ruedigermoeller.serialization.FSTClazzNameRegistry.decodeClass(FSTClazzNameRegistry.java:161) ~[fst-1.53.jar:na]
    at de.ruedigermoeller.serialization.FSTObjectInput.readClass(FSTObjectInput.java:879) ~[fst-1.53.jar:na]
    at de.ruedigermoeller.serialization.FSTObjectInput.instantiateEnum(FSTObjectInput.java:335) ~[fst-1.53.jar:na]
    at de.ruedigermoeller.serialization.FSTObjectInput.instantiateSpecialTag(FSTObjectInput.java:272) ~[fst-1.53.jar:na]
    at de.ruedigermoeller.serialization.FSTObjectInput.readObjectWithHeader(FSTObjectInput.java:254) ~[fst-1.53.jar:na]
    at de.ruedigermoeller.serialization.FSTObjectInput.readArray(FSTObjectInput.java:816) ~[fst-1.53.jar:na]
    at de.ruedigermoeller.serialization.FSTObjectInput.instantiateArray(FSTObjectInput.java:325) ~[fst-1.53.jar:na]
    at de.ruedigermoeller.serialization.FSTObjectInput.instantiateSpecialTag(FSTObjectInput.java:287) ~[fst-1.53.jar:na]
    at de.ruedigermoeller.serialization.FSTObjectInput.readObjectWithHeader(FSTObjectInput.java:254) ~[fst-1.53.jar:na]
    at de.ruedigermoeller.serialization.FSTObjectInput.readObjectFields(FSTObjectInput.java:522) ~[fst-1.53.jar:na]
    at de.ruedigermoeller.serialization.FSTObjectInput.instantiateAndReadNoSer(FSTObjectInput.java:402) ~[fst-1.53.jar:na]
    at de.ruedigermoeller.serialization.FSTObjectInput.readObjectWithHeader(FSTObjectInput.java:261) ~[fst-1.53.jar:na]
    at de.ruedigermoeller.serialization.FSTObjectInput.readObjectInternal(FSTObjectInput.java:230) ~[fst-1.53.jar:na]
    at de.ruedigermoeller.serialization.FSTObjectInput.readObject(FSTObjectInput.java:210) ~[fst-1.53.jar:na]
    at de.ruedigermoeller.serialization.FSTObjectInput.readObject(FSTObjectInput.java:165) ~[fst-1.53.jar:na]
    ... 33 common frames omitted
Caused by: java.lang.ClassNotFoundException: com.bvg.models.enums.Gender
    at java.net.URLClassLoader$1.run(URLClassLoader.java:372) ~[na:1.8.0_05]
    at java.net.URLClassLoader$1.run(URLClassLoader.java:361) ~[na:1.8.0_05]
    at java.security.AccessController.doPrivileged(Native Method) ~[na:1.8.0_05]
    at java.net.URLClassLoader.findClass(URLClassLoader.java:360) ~[na:1.8.0_05]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424) ~[na:1.8.0_05]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ~[na:1.8.0_05]
    at java.lang.Class.forName0(Native Method) ~[na:1.8.0_05]
    at java.lang.Class.forName(Class.java:340) ~[na:1.8.0_05]
    at de.ruedigermoeller.serialization.FSTClazzNameRegistry.classForName(FSTClazzNameRegistry.java:184) ~[fst-1.53.jar:na]
    ... 49 common frames omitted

초기 로딩 시 java.util.ConcurrentModificationException 발생.

안녕하세요. hibernate-redis 를 적용하여 사용하고 있는데,
초기 부트 타임 시 간헐적(?)으로 아래와 같은 Exception이 발생하고 있습니다.

java.util.ConcurrentModificationException: null
    at java.util.HashMap$HashIterator.nextEntry(HashMap.java:926) ~[na:1.7.0_51]
    at java.util.HashMap$KeyIterator.next(HashMap.java:960) ~[na:1.7.0_51]
    at org.hibernate.cache.redis.AbstractRedisRegionFactory$1.run(AbstractRedisRegionFactory.java:177) ~[hibernate-redis-1.5.7.jar:na]
    at java.lang.Thread.run(Thread.java:744) [na:1.7.0_51]

소스를 살펴보니

AbstractRedisRegionFactory.java에서 Set형인 'regionNames' 컬렉션이 'manageExpiration' 메소드에서 루핑을 하는 동안 다른 스레드가 'buildXXX' 메소드 안에서 추가를 해줘서 'ConcurrentModificationException'이 발생하는 것 같습니다. 'manageExpiration' 메소드 안에서 'regionNames' 변수를 동기화하거나 clone하여 루핑하면 일단 해결될 것 같은데....한번 확인 부탁드리겠습니다 :)

Fail to load cache properties

Something error.
o.h.cache.redis.util.JedisTool - Fail to load cache properties. cachePath=hibernate-redis.properties
java.lang.NullPointerException: null...

I use spring mvc
this my Hibernate configure

<property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">
                    org.hibernate.dialect.MySQLDialect
                </prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.format_sql">true</prop>
                <prop key="hibernate.c3p0.min_size">5</prop>
                <prop key="hibernate.c3p0.max_size">20</prop>
                <prop key="hibernate.c3p0.timeout">120</prop>
                <prop key="hibernate.c3p0.max_statements">100</prop>
                <prop key="hibernate.c3p0.acquire_increment">1</prop>
                <prop key="c3p0.testConnectionOnCheckout">true</prop>
                <prop key="c3p0.idleConnectionTestPeriod">18000</prop>
                <prop key="c3p0.maxIdleTime">25000</prop>
                <prop key="c3p0.idle_test_period">120</prop>
                <prop key="hibernate.cache.use_second_level_cache">true</prop>
                <prop key="hibernate.cache.cache.use_query_cache">true</prop>
                <prop key="hibernate.cache.region.factory_class">org.hibernate.cache.redis.SingletonRedisRegionFactory</prop>
                <prop key="hibernate.cache.region_prefix">hibernate</prop>
                <prop key="hibernate.generate_statistics">true</prop>
                <prop key="hibernate.cache.use_structured_entries">true</prop>
                <prop key="hibernate.transaction.factory_class">org.hibernate.engine.transaction.internal.jdbc.JdbcTransactionFactory</prop>
                <prop key="hibernate.cache.provider_configuration_file_resource_path">hibernate-redis.properties</prop>
            </props>
        </property>

and I change hibernate-redis.properties path to "WEB-INF/xx" "/xx", "E:/workspace absolute path/WEB-INF/xx" allway fail load

Support Java 6 in FST

FST support Java 6 in different artifact and package name.

To support Java 6 with FST, New FST Codec needed for Redisson.
Redisson using FST which support Java 7 or higher

hibernate.redis.properties file configure redis.password cant work

......
 # redis.timeout=2000
 redis.password=password

error logs message :

21:03:18.812 [Thread-11] WARN o.h.cache.redis.jedis.JedisClient - Error in Cache Expiration Method.
redis.clients.jedis.exceptions.JedisConnectionException: Could not get a resource from the pool
at redis.clients.util.Pool.getResource(Pool.java:42) ~[jedis-2.5.1.jar:na]
at redis.clients.jedis.JedisPool.getResource(JedisPool.java:84) ~[jedis-2.5.1.jar:na]
at org.hibernate.cache.redis.jedis.JedisClient.run(JedisClient.java:510) ~[hibernate-redis-1.6.1.jar:na]
at org.hibernate.cache.redis.jedis.JedisClient.expire(JedisClient.java:342) ~[hibernate-redis-1.6.1.jar:na]
at org.hibernate.cache.redis.AbstractRedisRegionFactory$1.run(AbstractRedisRegionFactory.java:177) [hibernate-redis-1.6.1.jar:na]
at java.lang.Thread.run(Thread.java:745) [na:1.8.0_60]
Caused by: redis.clients.jedis.exceptions.JedisDataException: ERR Client sent AUTH, but no password is set
at redis.clients.jedis.Protocol.processError(Protocol.java:113) ~[jedis-2.5.1.jar:na]
at redis.clients.jedis.Protocol.process(Protocol.java:131) ~[jedis-2.5.1.jar:na]
at redis.clients.jedis.Protocol.read(Protocol.java:200) ~[jedis-2.5.1.jar:na]
at redis.clients.jedis.Connection.readProtocolWithCheckingBroken(Connection.java:285) ~[jedis-2.5.1.jar:na]
at redis.clients.jedis.Connection.getStatusCodeReply(Connection.java:184) ~[jedis-2.5.1.jar:na]
at redis.clients.jedis.BinaryJedis.auth(BinaryJedis.java:2193) ~[jedis-2.5.1.jar:na]
at redis.clients.jedis.JedisFactory.makeObject(JedisFactory.java:67) ~[jedis-2.5.1.jar:na]
at org.apache.commons.pool2.impl.GenericObjectPool.create(GenericObjectPool.java:819) ~[commons-pool2-2.0.jar:2.0]
at org.apache.commons.pool2.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:429) ~[commons-pool2-2.0.jar:2.0]
at org.apache.commons.pool2.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:360) ~[commons-pool2-2.0.jar:2.0]
at redis.clients.util.Pool.getResource(Pool.java:40) ~[jedis-2.5.1.jar:na]
... 5 common frames omitted

if I don't set reds password , can work.
and I use redid-cli connect redid-server with password is ok !

is just some bug that skip test case ?

Redis 저장소를 Hashes 로 변경

Hashes key sub-key value 형식을 이용하여
region entity-key entity 로 저장한다.

region 삭제도 del region 으로 한번에 할 수 있다.
region 삭제 전 exists 로 삭제 여부를 판단할 수 있다.

기존의 entity 의 region 은 entity의 fullname 으로 강제되었는데, Hashes 를 이용하면,
지정된 region 을 사용할 수 있다.

Concurrent access

If two hibernate instance with hibernate-redis accesses concurrently at same resource, can occur a race condition?

  1. B make a slow query.
  2. A make a fast query and put a new element in cache, named test1 with value X;
  3. B finish its slow query and modify test1 element changing its value to Y.

But the most updated value is X.

Maven problem - Failure to find com.github.debop:hibernate-redis-parent:pom:1.6.0

Maven gives me an error when I try to build my project with hibernate-redis dependency. I have tried with hibernate-redis 1.6.0 and 1.5.9 versions and maven 3.0.4 and 3.2.1.

The maven gives me following error:
Failed to execute goal on project mdm-services: Could not resolve dependencies for project com.tmsw.mdm.services:mdm-services:war:1.0-SNAPSHOT: Failed to collect dependencies at com.github.debop:hibernate-redis:jar:1.6.0: Failed to read artifact descriptor for com.github.debop:hibernate-redis:jar:1.6.0: Failure to find com.github.debop:hibernate-redis-parent:pom:1.6.0 in http://dl.bintray.com/debop/maven was cached in the local repository, resolution will not be reattempted until the update interval of debop-releases-bintray has elapsed or updates are forced

Suggested dependencies for the readme

Hi just gone through the configuration with hibernate5/spring and detected some probably missed dependencies. Don't know but commenting just in case.

<dependency>
    <groupId>org.redisson</groupId>
    <artifactId>redisson</artifactId>
    <version>${redisson.version}</version>
</dependency>
<dependency>
    <groupId>com.github.debop</groupId>
    <artifactId>hibernate-redis</artifactId>
    <version>${hibernate-redis.version}</version>
    <exclusions>
        <exclusion>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-core</artifactId>
        </exclusion>
        <exclusion>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>de.ruedigermoeller</groupId>
    <artifactId>fst</artifactId>
    <version>${fst.version}</version>
</dependency>
<dependency>
    <groupId>org.xerial.snappy</groupId>
    <artifactId>snappy-java</artifactId>
    <version>${snappy-java.version}</version>
</dependency>

2.x doesn't seem to take in the expirySeconds into account.

I tried using the following config with the expiryInSeconds set to 7200 (2 hrs) but it's still expiring in 1 minute. I am using 2.x along with hibernate 5.1.0.FINAL.

Belong is my hibernate-redis.xml

##########################################################

properities for hibernate-redis

##########################################################

Redisson configuration file

redisson-config=conf/redisson.yaml

Cache Expiry settings

'hibernate5' is second cache prefix

'common', 'account' is actual region name

redis.expiryInSeconds.default=7200
redis.expiryInSeconds.hibernate5.common=7200

Allow configuration from hibernate configuration

The configuration is performed from hibernate-redis.properties configuration file. It should be great (for better integration with Spring Boot for example) if the keys could be loaded from the hibernate configuration that is given to the factory. The rationale could be that if we can't load the file (because it doesn't exist, then get the keys from the hibernate configuration.

add Chill (from Kryo) serializer

add another serializer (kryo or chill)
and compare with snappy.

  1. adopt chill
  2. decorator by snappy
  3. add configuration to use snappy and chill

Which Redis maxmemory policy eviction is appropraite

Hello,
Thank you for this great library. I have a question regarding redis configuration.

I'm trying to fine tune my setup and one of the thing which I need to configure is the redis maxmemory eviction policy. I noticed that hibernate-redis/redisson is not setting the ttl value on cache regions in Redis. What is the recommended eviction policy? Right now, I think allkeys-lru and allkeys-random are the only options since those would be the only ones which make sense. I was hoping to use volatile-ttl but there is no ttl on any of these redis keys.

org.hibernate.cache.redis.regions.RedisDataRegion#destroy 메소드에 관한 질문

먼저 제가 스스로 다른 Hibernate 캐시를 구현하면서 배성혁님의 소스를 많이 참조하고 있습니다. 그러면서 분석하고 배우고 그러고 있습니다. 고맙습니다.

org.hibernate.cache.redis.regions.RedisDataRegion#destroy 에 관한 질문입니다.
현재 이 메소드는 region을 삭제하는 것으로 보이는데요, ( hibernate의 다른 캐시 구현체들도 모두 그렇게 구현하고 있더군요). 문제는 이 메소드가 SessionFactory.close()가 호출될 때 모든 Region을 돌며 호출된다는 점입니다.

여러 웹 서버가 동일한 Redis 캐시를 바라보고 캐싱을 하는데 그 중에서 한 대의 웹서버가 종료되면, 그 순간 SessionFactory.close() 호출 -> 모든 RedisDataRegion 객체를 돌면서 destroy() 호출로 인해 모든 region이 삭제될 것으로 예상됩니다.

그렇게 되면 나머지 살아 있는 웹서비스들은 순간적으로 모든 캐시를 expire당하게 되어 순간적으로 급격한 성능 저하가 발생할 것으로 예상됩니다.

제가 보기엔 이게 Local 캐시용으로 마련된 메소드인 것 같습니다. redis 같은 분산 캐시 계열에서는 캐시 region 삭제 용도로 호출되면 안 될 것 같습니다.

한 번 확인을 부탁드립니다.

SingletonRedisRegionFactory is not loading in spring xml based config

I am trying to configure this with xml based config but it throwing error. here is my config file
<property name="hibernate.cache.use_second_level_cache" value="true" /> <property name="hibernate.cache.use_query_cache" value="true" /> <property name="hibernate.cache.region_prefix" value="hibernate" /> <property name="hibernate.cache.query_cache_factory" value="org.hibernate.cache.redis.hibernate5.SingletonRedisRegionFactory" /> <property name="hibernate.cache.provider_configuration_file_resource_path" value="statchat-app.properties"/>

but it is is throwing an error for constructor

Caused by: org.hibernate.boot.registry.selector.spi.StrategySelectionException: Could not instantiate named strategy class [org.hibernate.cache.redis.hibernate5.SingletonRedisRegionFactory] at org.hibernate.boot.registry.selector.internal.StrategySelectorImpl.resolveDefaultableStrategy(StrategySelectorImpl.java:170) at org.hibernate.boot.registry.selector.internal.StrategySelectorImpl.resolveDefaultableStrategy(StrategySelectorImpl.java:126) at org.hibernate.boot.internal.SessionFactoryBuilderImpl$SessionFactoryOptionsStateStandardImpl.<init>(SessionFactoryBuilderImpl.java:649) at org.hibernate.boot.internal.SessionFactoryBuilderImpl.<init>(SessionFactoryBuilderImpl.java:118) at org.hibernate.boot.internal.MetadataImpl.getSessionFactoryBuilder(MetadataImpl.java:135) at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:876) at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:60) at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:343) at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:319) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1637) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1574) ... 46 more Caused by: java.lang.InstantiationException: org.hibernate.cache.redis.hibernate5.SingletonRedisRegionFactory at java.lang.Class.newInstance(Class.java:427) at org.hibernate.boot.registry.selector.internal.StrategySelectorImpl.resolveDefaultableStrategy(StrategySelectorImpl.java:166) ... 56 more Caused by: java.lang.NoSuchMethodException: org.hibernate.cache.redis.hibernate5.SingletonRedisRegionFactory.<init>() at java.lang.Class.getConstructor0(Class.java:3082) at java.lang.Class.newInstance(Class.java:412) ... 57 more

Change some log message

Turns out that when the Redis server is stopped, an exception message is generated every second because the expiration timer is waked up every seconds. This leads to lot of messages being generated. I think this should be changed either by changing the severity of the message or by controlling the rate at which the message is generated (for example, generate only one message per slot of 30s)

Allow external configuration file

Calling the above

InputStream is = JedisTool.class.getClassLoader().getResourceAsStream(cachePath);

forces the configuration hibernate-redis.properties to be inside the classpath.
Would be great if it was possible to define the configuration file anywhere the system.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.