ehcache缓存框架
查询的操作最频繁,,某个线程很多的查询都是重复的,或者有些数据跨线程查询也是重复。
问题:造成数据库压力变大。传统的数据库查询效率就不高(网络、sql语句复杂),导致查询体验不好。
解决:使用缓存机制。
缓存用什么东西来弄?
传统有专门缓存框架:ehcache,memcache
NoSQL数据库:Redis、MongoDB
EhCache 是一个纯Java的进程内缓存框架,具有快速、精干等特点,是Hibernate中默认的CacheProvider。
整合Ehcache-优化性能-降低查询数据库的频率
Spring集成Ehcache:
配置Ehcache缓存管理器(EhcacheManager),将其注入给Spring平台缓存管理器(cachemanager),Spring平台缓存管理器再注入给Spring缓存注解驱动。代码中使用注解进行缓存。
Shiro集成Ehcache:
配置Ehcache缓存管理器(EhcacheManager),将其注入给Shiro缓存管理器(这里是shiro整合ehcache的缓存管理器),最后将Shiro的缓存管理器注入给Shiro安全管理器
1.通过maven坐标导入jar(ehcache和spring的context-support)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
2.配置ApplicationContext.xml (Shiro整合ehcache)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
3.BosRealm中添加注解
- 1
- 2
- 3
- 4
- 5
- 6
- 7
4.配置ehcache.xml
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
动态菜单优化
减少无用数据查询(减少SQL的发出)
问题:每次菜单生成的语句太多。生成了很多与功能权限菜单无关的语句,如角色等
解决:在Function的实体类中,使用@JSON(serialize=fase)
对每个用户菜单进行缓存
问题:每次刷新整个页面都会重新生成菜单,都会重新查询一次数据库。
解决方案:使用缓存。具体:使用spring 整合ehcache的缓存
1.使用maven坐标引入jar
略(上面已经引过了)
2.配置ApplicationContext.xml
- 1
- 2
- 3
- 4
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
3.编写ehcache.xml,添加一个新的缓存区域,如MenuSpringCache
4.在方法上添加注解
提示:spring的缓存管理器默认的key是方法名+参数,如果参数是个对象,那么会发生每次缓存的key都不一样,虽然数据的一样的。因此这种情况下,需要手动指定key
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
如添加权限,要清除缓存
- 1
- 2
- 3
- 4
- 5
- 6
- 7
Hibernate中使用ehcache
1.导入 jar 包:ehcache-1.5.0.jar/ commons-logging.jar/ backport-util-concurrent.jar
2.开启二级缓存(我要使用二级缓存)
3.确定二级缓存提供商(我要使用哪个二级缓存)
4.确定需要缓存内容
1>配置需要缓存的类
2>配置需要缓存的集合
5.配置 ehcache 自定义配置文件
引入Maven坐标
- 1
- 2
- 3
- 4
- 5
在 hibernate.cfg.xml 配置缓存,或者交由spring管理,在sessionFactory中配置
开启二级缓存
- 1
- 2
确定缓存提供商
- 1
确定缓存内容
- 1
- 2
- 3
- 4
- 5
ehcache 配置文件
文件名:ehcache.xml
参考官方文件配置
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
测试
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
查询缓存
查询缓存默认不使用。需要手动开启
查询缓存:将 HQL 语句与 查询结果进行绑定。通过 HQL 相同语句可以缓存内容。
默认情况 Query 对象只将查询结果存放在一级和二级缓存,不从一级或二级缓存获取。
查询缓存就是让 Query 可以从二级缓存获得内容。
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41