hibernate整合redis二级缓存问题

背景:
有一老项目采用的hibernate配合ehcache作为二级缓存,现因需求需要更换redis来做hibernate的二级缓存。大家不用问为什么不换掉hibernate,因为是老项目所以风险太大。
问题:
1、我按照网上做法导入了若干个jar包,见图:
图片说明
2、spring中sessionFactory也配置了二级缓存:

hibernate.cache.use_query_cache = true
hibernate.cache.use_second_level_cache = true
hibernate.cache.use_structured_entries = true
hibernate.cache.region_prefix = hibernate
hibernate.cache.region.factory_class = org.hibernate.cache.redis.hibernate5.RedisRegionFactory
hibernate.cache.provider_configuration_file_resource_path = hibernate-redis.properties

3、也分别创建了hibernate-redis.properties和redisson.yaml,内容分别如下
(1)hibernate-redis.properties:

 redisson-config = classpath:redisson.yaml 
redis.expiryInSeconds.default = 360
redis.expiryInSeconds.hibernate.common = 0
redis.expiryInSeconds.hibernate.account = 1200

(2)redisson.yaml

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

4、redis也正常运行
5、最后运行程序报了一个错:

 Caused by: com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.net.URI` out of START_ARRAY token
 at [Source: (URL); line: 14, column: 4] (through reference chain: org.redisson.config.Config["singleServerConfig"]->org.redisson.config.SingleServerConfig["address"])
    at com.fasterxml.jackson.databind.exc.MismatchedInputException.from(MismatchedInputException.java:63)
    at com.fasterxml.jackson.databind.DeserializationContext.reportInputMismatch(DeserializationContext.java:1342)
    at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1138)
    at com.fasterxml.jackson.databind.deser.std.StdDeserializer._deserializeFromArray(StdDeserializer.java:674)
    at com.fasterxml.jackson.databind.deser.std.FromStringDeserializer.deserialize(FromStringDeserializer.java:164)
    at com.fasterxml.jackson.databind.deser.impl.FieldProperty.deserializeAndSet(FieldProperty.java:136)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:288)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:151)
    at com.fasterxml.jackson.databind.deser.impl.MethodProperty.deserializeAndSet(MethodProperty.java:127)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:288)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:151)
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4013)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2959)
    at org.redisson.config.ConfigSupport.fromYAML(ConfigSupport.java:169)
    at org.redisson.config.Config.fromYAML(Config.java:754)
    at org.hibernate.cache.redis.client.RedisClientFactory.createRedisClient(RedisClientFactory.java:63)
    ... 57 more
不知道怎么解决了,希望有相关经验的大神能助我解惑。

5个回答

删掉了,虽然不报错了,但一运行程序(包括Hibernate查询数据库的程序),就会报错,如下:

 Caused by: java.lang.AbstractMethodError: org.hibernate.cache.redis.hibernate5.regions.RedisQueryResultsRegion.get(Lorg/hibernate/engine/spi/SharedSessionContractImplementor;Ljava/lang/Object;)Ljava/lang/Object;
    at org.hibernate.cache.internal.StandardQueryCache.getCachedResults(StandardQueryCache.java:245) ~[hibernate-5.3.5.jar:?]
    at org.hibernate.cache.internal.StandardQueryCache.get(StandardQueryCache.java:161) ~[hibernate-5.3.5.jar:?]
    at org.hibernate.loader.Loader.getResultFromQueryCache(Loader.java:2619) ~[hibernate-5.3.5.jar:?]
    at org.hibernate.loader.Loader.listUsingQueryCache(Loader.java:2527) ~[hibernate-5.3.5.jar:?]
    at org.hibernate.loader.Loader.list(Loader.java:2499) ~[hibernate-5.3.5.jar:?]
    at org.hibernate.loader.criteria.CriteriaLoader.list(CriteriaLoader.java:109) ~[hibernate-5.3.5.jar:?]
    at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1936) ~[hibernate-5.3.5.jar:?]
    at org.hibernate.internal.CriteriaImpl.list(CriteriaImpl.java:370) ~[hibernate-5.3.5.jar:?]
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) ~[spring-5.0.8.jar:?]
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:746) ~[spring-5.0.8.jar:?]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163) ~[spring-5.0.8.jar:?]
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:294) ~[spring-5.0.8.jar:?]
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98) ~[spring-5.0.8.jar:?]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185) ~[spring-5.0.8.jar:?]
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:688) ~[spring-5.0.8.jar:?]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.8.0_144]
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[?:1.8.0_144]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[?:1.8.0_144]
    at java.lang.reflect.Method.invoke(Unknown Source) ~[?:1.8.0_144]
    at ognl.OgnlRuntime.invokeMethod(OgnlRuntime.java:871) ~[ognl-3.0.19.jar:?]
    at ognl.OgnlRuntime.callAppropriateMethod(OgnlRuntime.java:1294) ~[ognl-3.0.19.jar:?]
    ... 92 more

这个错儿我也查了一下,没找到相似的。

weixin_42456466
祗是辉哥哥 应该是jar包问题,重新引吧
接近 2 年之前 回复

问题就出在redisson.yaml第14行,地址错误,你试着把双引号或者中括号去掉试试。

HongKunCheng
小侠csdnn 不行呀,详见楼下↓
接近 2 年之前 回复
ainiburuqusi
ainiburuqusi 还有redis配置启动IP是否是127.0.0.1,还是外网IP
接近 2 年之前 回复

ainiburuqusi 不行呀,我试了单独去年引号或中括号,或者都去掉,也要报错。另外网上还有另一种写法:

   address: 
   - "redis://127.0.0.1:6379"

也不行,也报同样的错。
另外redis配置的IP就是127.0.0.1,不是外网IP,redis.conf:

 bind 127.0.0.1
HongKunCheng
小侠csdnn 还是有问题,详见楼下↓
接近 2 年之前 回复
ainiburuqusi
ainiburuqusi address: "redis://127.0.0.1:6379",具体参考下https://github.com/debop/hibernate-redis这个是官方文档。
接近 2 年之前 回复

我看了下源码,address格式是这样的。图片说明,所以用字符串就行了。
但是你这个异常信息是json格式转换失败。你这没有贴json转换的代码,不过你应该知道在哪里打断点解决了吧

HongKunCheng
小侠csdnn 还是有问题,详见楼下↓
接近 2 年之前 回复
weixin_42456466
祗是辉哥哥 上面返回的格式是[uri],但是转换为json的时候会把[]当成json数组了。所以就报错了。你要在这个值转换json之前把[]去掉就行了。
接近 2 年之前 回复

我照着官方提供的redisson.yaml改了配置,现在是这样:

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

这次报错信息变了,变成了:

Sep 13, 2018 11:26:39 AM org.apache.catalina.core.StandardContext listenerStart
SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'articleHelper': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [spring.xml]: Invocation of init method failed; nested exception is org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.spi.CacheImplementor]
    at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:321)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1341)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:572)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:495)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:759)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:869)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:409)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:291)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:103)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4861)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5322)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1408)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1398)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [spring.xml]: Invocation of init method failed; nested exception is org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.spi.CacheImplementor]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1699)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:573)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:495)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:251)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1135)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1062)
    at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.autowireResource(CommonAnnotationBeanPostProcessor.java:507)
    at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.getResource(CommonAnnotationBeanPostProcessor.java:485)
    at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor$ResourceElement.getResourceToInject(CommonAnnotationBeanPostProcessor.java:619)
    at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:186)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:91)
    at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:318)
    ... 22 more
Caused by: org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.spi.CacheImplementor]
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:271)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:233)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210)
    at org.hibernate.service.internal.SessionFactoryServiceRegistryImpl.getService(SessionFactoryServiceRegistryImpl.java:80)
    at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:243)
    at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:462)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:710)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:726)
    at org.springframework.orm.hibernate5.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:533)
    at org.springframework.orm.hibernate5.LocalSessionFactoryBean.afterPropertiesSet(LocalSessionFactoryBean.java:517)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1758)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1695)
    ... 37 more
Caused by: org.hibernate.cache.CacheException: java.lang.RuntimeException: com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "dnsMonitoring" (class org.redisson.config.SingleServerConfig), not marked as ignorable (27 known properties: "subscriptionsPerConnection", "keepAlive", "sslKeystorePassword", "retryInterval", "retryAttempts", "pingTimeout", "reconnectionTimeout", "pingConnectionInterval", "connectTimeout", "password", "sslProvider", "timeout", "failedAttempts", "connectionMinimumIdleSize", "idleConnectionTimeout", "sslTruststorePassword", "sslEnableEndpointIdentification", "address", "sslTruststore", "clientName", "subscriptionConnectionPoolSize", "connectionPoolSize", "subscriptionConnectionMinimumIdleSize", "sslKeystore", "tcpNoDelay", "dnsMonitoringInterval", "database"])
 at [Source: (URL); line: 22, column: 23] (through reference chain: org.redisson.config.Config["singleServerConfig"]->org.redisson.config.SingleServerConfig["dnsMonitoring"])
    at org.hibernate.cache.redis.hibernate5.RedisRegionFactory.start(RedisRegionFactory.java:54)
    at org.hibernate.cache.spi.RegionFactory.start(RegionFactory.java:63)
    at org.hibernate.internal.CacheImpl.<init>(CacheImpl.java:71)
    at org.hibernate.engine.spi.CacheInitiator.initiateService(CacheInitiator.java:28)
    at org.hibernate.engine.spi.CacheInitiator.initiateService(CacheInitiator.java:20)
    at org.hibernate.service.internal.SessionFactoryServiceRegistryImpl.initiateService(SessionFactoryServiceRegistryImpl.java:59)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:259)
    ... 48 more
Caused by: java.lang.RuntimeException: com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "dnsMonitoring" (class org.redisson.config.SingleServerConfig), not marked as ignorable (27 known properties: "subscriptionsPerConnection", "keepAlive", "sslKeystorePassword", "retryInterval", "retryAttempts", "pingTimeout", "reconnectionTimeout", "pingConnectionInterval", "connectTimeout", "password", "sslProvider", "timeout", "failedAttempts", "connectionMinimumIdleSize", "idleConnectionTimeout", "sslTruststorePassword", "sslEnableEndpointIdentification", "address", "sslTruststore", "clientName", "subscriptionConnectionPoolSize", "connectionPoolSize", "subscriptionConnectionMinimumIdleSize", "sslKeystore", "tcpNoDelay", "dnsMonitoringInterval", "database"])
 at [Source: (URL); line: 22, column: 23] (through reference chain: org.redisson.config.Config["singleServerConfig"]->org.redisson.config.SingleServerConfig["dnsMonitoring"])
    at org.hibernate.cache.redis.client.RedisClientFactory.createRedisClient(RedisClientFactory.java:67)
    at org.hibernate.cache.redis.client.RedisClientFactory.createRedisClient(RedisClientFactory.java:92)
    at org.hibernate.cache.redis.hibernate5.AbstractRedisRegionFactory.createRedisClient(AbstractRedisRegionFactory.java:65)
    at org.hibernate.cache.redis.hibernate5.RedisRegionFactory.start(RedisRegionFactory.java:48)
    ... 54 more
Caused by: com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "dnsMonitoring" (class org.redisson.config.SingleServerConfig), not marked as ignorable (27 known properties: "subscriptionsPerConnection", "keepAlive", "sslKeystorePassword", "retryInterval", "retryAttempts", "pingTimeout", "reconnectionTimeout", "pingConnectionInterval", "connectTimeout", "password", "sslProvider", "timeout", "failedAttempts", "connectionMinimumIdleSize", "idleConnectionTimeout", "sslTruststorePassword", "sslEnableEndpointIdentification", "address", "sslTruststore", "clientName", "subscriptionConnectionPoolSize", "connectionPoolSize", "subscriptionConnectionMinimumIdleSize", "sslKeystore", "tcpNoDelay", "dnsMonitoringInterval", "database"])
 at [Source: (URL); line: 22, column: 23] (through reference chain: org.redisson.config.Config["singleServerConfig"]->org.redisson.config.SingleServerConfig["dnsMonitoring"])
    at com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException.from(UnrecognizedPropertyException.java:60)
    at com.fasterxml.jackson.databind.DeserializationContext.handleUnknownProperty(DeserializationContext.java:822)
    at com.fasterxml.jackson.databind.deser.std.StdDeserializer.handleUnknownProperty(StdDeserializer.java:1152)
    at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.handleUnknownProperty(BeanDeserializerBase.java:1589)
    at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.handleUnknownVanilla(BeanDeserializerBase.java:1567)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:294)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:151)
    at com.fasterxml.jackson.databind.deser.impl.MethodProperty.deserializeAndSet(MethodProperty.java:127)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:288)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:151)
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4013)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2959)
    at org.redisson.config.ConfigSupport.fromYAML(ConfigSupport.java:169)
    at org.redisson.config.Config.fromYAML(Config.java:754)
    at org.hibernate.cache.redis.client.RedisClientFactory.createRedisClient(RedisClientFactory.java:63)
    ... 57 more 

我尝试把dnsMonitoring这个参数删掉,还是有报错,我想既然官方有这个参数,那它肯定是有作用的。

HongKunCheng
小侠csdnn 还是有问题,详见楼下↓
接近 2 年之前 回复
weixin_42456466
祗是辉哥哥 提示不识别这个参数,那你就删掉。如果是官网提供的那就是你所用的版本和官网提供这个配置的版本不一致。
接近 2 年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问