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包问题,重新引吧
大约一年之前 回复

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

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

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

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

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

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

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

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

我照着官方提供的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 还是有问题,详见楼下↓
大约一年之前 回复
weixin_42456466
祗是辉哥哥 提示不识别这个参数,那你就删掉。如果是官网提供的那就是你所用的版本和官网提供这个配置的版本不一致。
大约一年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
MyBatis -- 整合Redis二级缓存
一。MyBatis一级二级缓存        一级缓存:          MyBatis一级缓存为SqlSession级别的缓存,默认开启,相同的SqlSession对象查询相同条件的结果时,如果存在一级缓存,那么只会访问数据库一次,一级缓存在sqlSession关闭后失效,调用cleanCache后会被清除,执行过增删改后缓存也会被清除。注意:一级缓存不能跨session      ...
SSM整合Redis实现二级缓存
新增整合Redis模块提查询效率 pom.xml applicationcontext.xml 新增redisCatcheTransfer类 最后相应的javaBean实现序列化接口,Mybatis配置文件开启二级缓存,并且在相应的xxxMapper.xml中开启缓存,例如: Mybatis配置文件开启缓存:
mybatis整合redis实现二级缓存
一、整合ehcache 为什么需要缓存?提高程序的性能。 mybatis整合ehcache与hibernate的ehcache二级缓存相似  https://blog.csdn.net/oydl_1234/article/details/83625046 1、导入相关的依赖 &amp;lt;!--spring对ehcache的相关支持--&amp;gt; &amp;lt;dependency&amp;gt; ...
Redis作为hibernate的二级缓存的demo
1.使用背景    因客户需求,需要将现在的项目缓存架构换掉,现在使用的memcached缓存服务器。由于memcached出现了一些bug,客户要求换成Redis缓存服务器。所用的项目是spring+springmvc+hibernate4.18架构。2.引入jar包    所需的jar:    或者使用maven下载依赖&amp;lt;dependency&amp;gt; &amp;lt;groupId&amp;...
SSM+redis整合(mybatis整合redis做二级缓存)
     SSM:是Spring+Struts+Mybatis ,另外还使用了PageHelper    前言:   这里主要是利用redis去做mybatis的二级缓存,mybaits映射文件中所有的select都会刷新已有缓存,如果不存在就会新建缓存,所有的insert,update操作都会更新缓存。(这里需要明白对于注解写的SQL语句不会操作缓存,我的增加方法是注解写的就没有清空缓存...
hibernate整合Ehcache 实现二级缓存
一.hibernate缓存 有一级缓存、二级缓存。 目的是为了减少对数据库的访问次数,提升程序执行效率! 1 一级缓存 session Hibernate默认是开启一级缓存的,是基于Session的缓存,缓存内容只在当前session有效,session关闭,缓存内容失效! 特点: 作用范围较小! 缓存的事件短。 缓存效果不明显。 2 二级缓存 (可拔插式,可开可不开) hibernate...
hibernate学习篇——二级缓存,hibernate 整合ehcache
12
mybatis整合ehcache与spring整合Redis实现二级缓存
1、mybatis整合ehcache实现二级缓存 (1)导入相关依赖 &lt;!--spring对ehcache的相关支持--&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spr...
Mybatis整合ehcache Redis实现二级缓存
 为什么需要缓存  拉高程序的性能   什么样的数据需要缓存 很少被修改或根本不改的数据,业务场景比如:耗时较高的统计分析sql、电话账单查询sql等   ehcache的使用   导入相关依赖       &amp;lt;dependency&amp;gt;           &amp;lt;groupId&amp;gt;net.sf.ehcache&amp;lt;/groupId&amp;gt;         &amp;lt;a...
SpringBoot整合ehcache和redis实现二级缓存
简要说明:ehcache是内存缓存,在本地jvm内存中,十分高效,但是如果缓存数据都存在jvm中,内存是不够用的,于是使用到了redis数据库缓存,redis是键值对数据库,也比较高效,如果仅用redis做缓存,则存在频繁的网络IO读写,因为一般的会将redis部署在一个单独的服务器上,或者是集群部署。所以我们结合两者的特性,优先使用ehcache缓存,当ehcache中没有数据时,再向redis...
redis作为mybatis二级缓存整合讲解(中)
这是一套2019录制的关于Redis分布式缓存和Springboot深度整合的视频,课堂巧用类比法对比了Redis和Mysql、MongoDB、Memcached等其他<br />rn&nbsp;数据库的区别,从学员角度出发,通过各种方法让学员无缝学习和掌握。课程主要包括部分:NOSQL Redis分布式缓存概念,分布式缓存Redis内存管理<br />rn&nbsp;方案和持久化策略,实操讲解Redis五种数据类型以及Redis消息订阅,Redis事务和Mysql事务异同,以及Mysql事务隔离<br />rn&nbsp;机制的实现原理和MVCC,Springboot与Redis深度整合,Redis api源码剖析,手把手带你编写Springboot Cache ,Redis如何扛住万级访问,Redis实战如何实现高并发高可用排行榜等。同时在学习的过程中有任何不明白的地方,加客服qq351228901都可以进群向我咨询,我会积极帮助大家解决问题。<br />
Hibernate二级缓存使用问题
什么样的数据适合存放到第二级缓存中?   rn1 很少被修改的数据   rn2 不是很重要的数据,允许出现偶尔并发的数据   rn[color=#800000]3 不会被并发访问的数据  [/color] rn4 常量数据   rnrn第三条不是很理解,为什么被并发访问的数据不适合放到二级缓存中?rn还是说会被并发访问并且修改的数据不适合放在二级缓存里?rn这里是一个数据实效性问题么?
hibernate 二级缓存的问题~~~~~~~~~~~~~
[color=#FF0000][/color]我想用二级缓存,有点问题搞不明白 求教中rn[color=#FF0000]Person.hbm.xml[/color]rnrn[code=XML]rnrnrn rn [color=#FF0000][/color]rn rn rn rn rn rnrn[/code]rnrnrn[color=#FF0000]hibernate.hbm.xml[/color]rnrn[code=XML]rntruernorg.hibernate.cache.EhCacheProviderrntruern[/code]rnrnehcache.xmlrn[code=XML]rnrn[/code]rnrn测试类rn[code=Java]rnpublic class One2One rnrn public static void main(String[] args) rnrn addPersonAndIdCard2();rn check();rn rn public static void addPersonAndIdCard2() rnrn Session s= HiberUtil.getSession();rn Transaction t = s.beginTransaction();rn tryrn Person person = new Person();rn person.setName("sunyaozong");rn rn s.save(person); rn t.commit();rn catch(HibernateException e)rn if(t!=null)rn t.rollback();rn rn throw e;rn finallyrn if(s!=null)rn rn s.close();rn rn rn rnrn public static void check()rn Session s= null;rn Transaction t =null;rn tryrn s= HiberUtil.getSession();rn t = s.beginTransaction();rn rnrn //s.getSessionFactory().evict(Person.class); //语句(1)rn Person p1 =(Person)s.get(Person.class, 1);//语句(2)rn System.out.println(""+p1.getName());rn s.clear(); //语句(3)rn Person p2 =(Person)s.get(Person.class, 1); //语句(4) rn System.out.println(""+p2.getName());rn catch(HibernateException e)rn if(t!=null)rn t.rollback();rn rn throw e;rn finallyrn if(s!=null)rn s.close();rn rn rn tryrn s= HiberUtil.getSession();rn t = s.beginTransaction();rn s.getSessionFactory().evict(Person.class);//语句(5)rn Person p2 =(Person)s.get(Person.class, 1); //语句(6) rn System.out.println(""+p2.getName());rn catch(HibernateException e)rn if(t!=null)rn t.rollback();rn rn throw e;rn finallyrn if(s!=null)rn s.close();rn rn rn Statistics st =s.getSessionFactory().getStatistics();rn System.out.println(st);rn System.out.println("put:"+st.getSecondLevelCachePutCount());rn System.out.println("hit:"+st.getSecondLevelCacheHitCount());rn System.out.println("miss:"+st.getSecondLevelCacheMissCount()); rn rnrnrn[/code]rnrn测试结果rn[code=Java]rnHibernate: select idcard0_.person_id as person1_3_0_, idcard0_.name as name3_0_ from idcard idcard0_ where idcard0_.person_id=?rnsunyaozongrnHibernate: select idcard0_.person_id as person1_3_0_, idcard0_.name as name3_0_ from idcard idcard0_ where idcard0_.person_id=?rnsunyaozongrnHibernate: select person0_.id as id2_1_, person0_.name as name2_1_, idcard1_.person_id as person1_3_0_, idcard1_.name as name3_0_ from Person person0_ left outer join idcard idcard1_ on person0_.id=idcard1_.person_id where person0_.id=?rnsunyaozongrnStatistics[start time=1268924734687,sessions opened=3,sessions closed=3,transactions=1,successful transactions=1,optimistic lock failures=0,flushes=1,connections obtained=3,statements prepared=5,statements closed=5,second level cache puts=2,second level cache hits=2,second level cache misses=1,entities loaded=1,entities updated=0,entities inserted=1,entities deleted=0,entities fetched=2,collections loaded=0,collections updated=0,collections removed=0,collections recreated=0,collections fetched=0,queries executed to database=0,query cache puts=0,query cache hits=0,query cache misses=0,max query time=0]rnput:2rnhit:2rnmiss:1rnrn[/code]rnrn=============rn问题:这里需要到数据库当中查询三次,我是理解的 但是 put=2,hit=2,miss=1 都是为什么? 能不能解释一下呢?rn 为什么不清理二级缓存(注释掉语句5)之后 put=1,hit=3,miss=0了?rn 究竟是怎么回事?求指点rnrn
hibernate二级缓存问题
错误信息rnException in thread "main" java.lang.NoClassDefFoundError: com/opensymphony/oscache/base/Configrn at org.hibernate.cache.OSCacheProvider.(OSCacheProvider.java:33)rn at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)rn at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)rn at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)rn at java.lang.reflect.Constructor.newInstance(Unknown Source)rn at java.lang.Class.newInstance0(Unknown Source)rn at java.lang.Class.newInstance(Unknown Source)rn at org.hibernate.cfg.SettingsFactory.createCacheProvider(SettingsFactory.java:327)rn at org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:219)rn at org.hibernate.cfg.Configuration.buildSettings(Configuration.java:1881)rn at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1174)rn at com.lilong.hibernate.dao.HibernateSessionFactory.rebuildSessionFactory(HibernateSessionFactory.java:66)rn at com.lilong.hibernate.dao.HibernateSessionFactory.getSession(HibernateSessionFactory.java:49)rn at com.lilong.hibernate.dao.HibernateSessionFactory.add(HibernateSessionFactory.java:118)rn at com.lilong.hibernate.CacheTest.addUser(CacheTest.java:67)rn at com.lilong.hibernate.CacheTest.main(CacheTest.java:20)rnrnhibernate.cfg.xml配置内容:rntruernorg.hibernate.cache.OSCacheProviderrn已存在hibernate3.jar包,oscache.properties在src目录下rn请大虾们帮下忙!
关于hibernate二级缓存问题
二级缓存只能对通过ID查询的语句起作用?rn只对这样的语句 hql="from ShopBean as shop where shop.s_id =123"; 起作用?rn我底下的语句不行?怎么才能让下面的语句也使用二级缓存?rnrn[code=Java]rnList shops;rnString hql="from ShopBean as shop where shop.s_level like '%"+level+"' and shop.s_check='"+check+"'";rnQuery query=session.createQuery(hql);rnshops=query.list();rnreturn shops;rn[/code]
hibernate 二级缓存问题
我用的是ehcache-1.2.3.jar包rn报错是:rnrnjava.lang.NoClassDefFoundErrorrn at com.bjsxt.hibernate.Cache2Test.testCache1(Cache2Test.java:29)rn at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)rn at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)rn at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)rn at java.lang.reflect.Method.invoke(Unknown Source)rn at junit.framework.TestCase.runTest(TestCase.java:154)rn at junit.framework.TestCase.runBare(TestCase.java:127)rn at junit.framework.TestResult$1.protect(TestResult.java:106)rn at junit.framework.TestResult.runProtected(TestResult.java:124)rn at junit.framework.TestResult.run(TestResult.java:109)rn at junit.framework.TestCase.run(TestCase.java:118)rn at org.eclipse.jdt.internal.junit.runner.junit3.JUnit3TestReference.run(JUnit3TestReference.java:130)rn at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)rn at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:460)rn at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:673)rn at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:386)rn at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:196)rnrn我看了一下源码,似乎hibernate3.3的org.hibernate.cache.CacheProvider接口已经不建议使用了,不知道是不是这个包的问题;
hibernate二级缓存问题。
我把 List teams = meaulInter.executeQuery("from Team"); 这个查询出来的n结果放到了二级缓存里面。n然后这个Team对象 跟 一个 Page 对象 是1对多关系,因此,当我要引出Team对象对应的多方Page对象的属性的时候,会向数据库发出查询语句,我想把查询的结果放到缓存里面我该怎么做,才会令到懒加载的时候能从缓存中取出?
关于hibernate的二级缓存的问题
TestForm testForm = (TestForm) form;// TODO Auto-generated method stubrnrn Session session = sf.openSession();rn Query query = session.createQuery("from Emp");rn List s=query.list();rn rn rn rnrn for (int i = 0; i < 10; i++) rn query.list();rn rn rn session.close();rnrn return null;rn这是我的代码rn我用的是ehcache,rnehcache.xml放在src下,在emp.hbm.xml加了rn运行时,rn还是执行了11条sql语句,为什么啊!!
hibernate二级缓存初始化问题
这个问题我也无语了,不过还是解决了 hibernate给出的etc目录如下: 官方文档写的: hibernate.cache.region.factory_class org.hibernate.cache.internal.EhCacheRegionFactory 然而并没有这个目录: 按官方文档配置,报错如下: Exception in thread "main" java...
hibernate二级缓存的问题
1.rntimeToIdleSeconds当缓存闲置n秒后销毁rntimeToLiveSeconds当缓存存活n秒后销毁rn这两个参数什么意思呢,不太理解rnrnrn2.rndiskPersistentrndiskExpiryThreadIntervalSecondsrnmemoryStoreEvictionPolicyrn这三个参数是什么意思
Hibernate二级缓存问题
问题:使用Hibernate二级缓存时,在session1里面查询出book表的所有book,然后把session1关闭;开启一个新的session2,根据bId查询一个book;按理来说,此时是会从缓存中拿那个book对象,但实验的情况却是又发送了sql语句从数据库查询。rnrn缓存的配置如下:rnHibernate.cfg.xml中:rn [img=https://img-bbs.csdn.net/upload/201403/23/1395587977_792525.png][/img]rnrnBook.hbm.xml中:rn [img=https://img-bbs.csdn.net/upload/201403/23/1395587996_227663.png][/img]rnrn实验的代码:rn [img=https://img-bbs.csdn.net/upload/201403/23/1395588010_300721.png][/img]rn
hibernate的二级缓存问题
A表和B表,A多对B一。rnA表:数据量达千万,查询和更新都很平凡。rnB表:数据量1000以内,查询频繁,几乎不更新。rnrn我现在想将B表的数据放到二级缓存里,A用lazy=false来关联B。我觉得这样很方便,因为不仅A经常要连带B一起查询,其他地方也经常要查询B,我觉得这个缓存应该用得没问题吧?rnrn在这里询问下大家的意见,这样使用是否有问题?
Hibernate二级缓存的问题
save之后的对象会放到二级缓存中吗?
Hibernate的二级缓存问题
问题,Hibernate是否默认启用了SessionFactory级别的二级缓存。rn实验代码如下:rn[code=Java]rnpackage hibernatetest;rnrnimport packagesrnpublic class CacheTest rnrn public static void main(String[] args) throws Exception rnrn Configuration conf = new Configuration();rn conf.addClass(User.class);rn SessionFactory sf = conf.configure().buildSessionFactory();rnrn Thread t1 = new Thread(new UserThread(sf));rn Thread t2 = new Thread(new UserThread(sf));rn t1.start();rn t2.start();rn t1.join();rn t2.join();rn sf.close();rnrn rnrnrnrnclass UserThread implements Runnable rnrn SessionFactory sf;rnrn public UserThread(SessionFactory sf) rn this.sf = sf;rn rnrn public void run() rn Session session = sf.openSession();rn System.out.println(Thread.currentThread().getName() + " "rn + session.hashCode());rn Transaction tx = session.beginTransaction();rn User user = (User) session.load(User.class, "1");rn System.out.println(Thread.currentThread().getName() + " "rn + user.hashCode());rn tx.commit();rn session.close();rnrn rnrn[/code]rnHibernate配置文件如下:rn[code=XML]rnrnrnrnrnrnrn rn rn oracleDriverrn rn rn jdbc:oracle:thin:@localhost:1521:masterrn rn xxxxxrn xxxxxrn rn oracle.jdbc.driver.OracleDriverrn rn rn org.hibernate.dialect.Oracle10gDialectrn rn rnrnrn[/code]rn自己在做测试之前的想法是:Hibernate的二级缓存是必须经过明确配置才能启用的。也就是说上述两个线程输出的User的hashCode应该是不一样的。但是运行结果如下:rn[color=#FF0000]Thread-0 1352077rnThread-1 8012937rnThread-0 -175096011rnThread-1 -175096011[/color]rn很明显,这两个线程当中的session是不一样的。但是后取数据的那个线程似乎是从二级缓存当中取得数据,否则两个User的hashCode值不可能一样。rnHibernate似乎自动启用了Application级别的二级缓存。那么像webapp这样的应用中,一个Object自动被载入了Hibernate二级缓存,在没有被清理之前,它是否也一直存在——个人感觉这点对长对话的处理很有影响。rn请高手解惑!rn十分感谢!rn
hibernate 二级缓存的问题
我配置好Hibernate二级缓存后,使用时不知为什么在控制器上有如下的信息rn2008-12-05 16:04:55,980 WARN [org.hibernate.cache.EhCacheProvider] -Could not find configuration [org.hibernate.cache.UpdateTimestampsCache]; using defaults.rn2008-12-05 16:04:55,980 WARN [org.hibernate.cache.EhCacheProvider] -Could not find configuration [org.hibernate.cache.StandardQueryCache]; using defaults.rnHibernate: select student0_.id as id0_, student0_.name as name0_, student0_.age as age0_ from student student0_ where student0_.id=3rnsize==>1rntestrnrn请问这是为什么???谢谢啊
redis与ssm整合(mybatis二级缓存)单机版
1.首先在pom.xml中增加需要的redis jar包 &amp;lt;dependency&amp;gt; &amp;lt;groupId&amp;gt;redis.clients&amp;lt;/groupId&amp;gt; &amp;lt;artifactId&amp;gt;jedis&amp;lt;/artifactId&amp;gt; &amp;lt;version&amp;gt;2.9.0&amp;lt;/v...
springboot2.x整合redis做mybatis的二级缓存
springboot整合redis做mybatis的二级缓存,含有自定义key,自定义过期时间,自定义序列化方式
spring boot与mybatis与二级缓存redis整合
目录 零、spring boot与mybatis整合 一、版本 二、目录树与jar包 三、配置文件 四、实体类 五、缓存类 六、xml文件使用二级缓存 七、使用二级缓存结果 零、spring boot与mybatis整合 https://blog.csdn.net/xushiyu1996818/article/details/89036186 一、版本 使用java1...
hibernate中的二级缓存的问题
缓存配置文件 timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true" diskPersistent="false" diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU" /> timeToIdleSeconds="
hibernate的二级缓存,有点问题
现在有两个表,用户表和权限表,一对多关系,lazy="false"懒加载rn查询用户表时,自动加载权限表的数据rn设置了rnrn我把两个表都设置为二级缓存,执行查询用户时,理论上第一次会执行sql语句,第二次就直接从内存里查rnrn现在的问题是,查询用户表正常,只从数据库查一次,可是权限还是每次都从数据库查询,权限表的缓存没起作用,怎么回事,一对多懒加载不能使用二级缓存吗
Spring 整合 Hibernate 时启用二级缓存
写在前面:   1. 本例使用 Hibernate3 + Spring3;   2. 本例的查询使用了 HibernateTemplate; 1. 导入 ehcache-x.x.x.jar 包; 2. 在 applicationContext.xml 文件中找到 sessionFactory 相应的配置信息并在设置 hibernateProperties 中添加如下
hibernate二级缓存
完整的工程,可导入运行。测试内容为一级缓存和2级缓存。运行通过。配简单注解说明
Hibernate 二级缓存
Hibernate 二级缓存
hibernate 二级缓存
做一个hibernate 二级缓存的例子,其中都已经加了注释,一看就明白,数据库需要自己建
Hibernate二级缓存
Hibernate二级缓存Hibernate二级缓存Hibernate二级缓存Hibernate二级缓存Hibernate二级缓存
Hibernate的二级缓存
1.1 Hibernate的二级缓存: Hibernate缓存分类: 一、Session缓存(又称作事务缓存):Hibernate内置的,不能卸除。 缓存范围:缓存只能被当前Session对象访问。缓存的生命周期依赖于Session的生命周期,当Session被关闭后,缓存也就结束生命周期。 二、SessionFactory缓存(又称作应用缓存):使用第三方插件,可插拔。 缓存范围:缓存
相关热词 c#检测非法字符 c#双屏截图 c#中怎么关闭线程 c# 显示服务器上的图片 api嵌入窗口 c# c# 控制网页 c# encrypt c#微信网页版登录 c# login 居中 c# 考试软件