发表于: 2017-07-12 17:59:11
1 1419
今天:
阅读了《精通Spring 4.x》书中的Spring Cache一章的内容,对缓存,在Java中如何实现缓存,在Spring中如何实现缓存有了更深的理解。
Java对象只有实现了序列化接口,才能被JVM序列化。对象本身不用实现接口的任何方法。
缓存应该加在服务层。
缓存的基本逻辑是,先查缓存,缓存中没有就查数据库,再把查到的插入缓存中。
Spring本身提供默认的缓存管理注解。直接在服务层使用缓存注解,可以和缓存逻辑进行分离。
在Service方法上加入并标明缓存的名字,@Cacheable(cacheNames = “users” )。
只有public方法可以被缓存。
缓存的键,Spring有自带的SimpleKeyGenerator根据方法名和入参自动生成。
用了现在比较流行的Redisson。Redisson提供了将Redis无缝整合到Spring框架的能力。Redisson完整的实现了Spring框架里的缓存机制(Spring Cache Abstraction)。
Redisson有很多功能,这里只用它和Spring Cache整合的功能。其他以后有需要了再研究。
导入Redisson包:
添加一个配置文件类,配置方法如下,没有配置的都使用默认(Redis如果不在本地,需要在Redis配置文件中把127.0.0.1注解掉,类似MySQL):
直接在Service层把想要缓存返回值的方法上面加上@Cacheable即可,Spring Cache会自动使用Redisson进行缓存,自动实现缓存的逻辑(先查缓存,缓存没有查服务器,再插入缓存中):
对自己两台服务器(一台金山一台阿里)分别进行不缓存和缓存的测试,数据库在金山。都为两线程。
Label | # Samples | Average | Median | 90% Line | 95% Line | 99% Line | Min | Max | Error % | Throughput | Received KB/sec | Sent KB/sec |
addUser | 4822 | 90 | 46 | 262 | 331 | 589 | 20 | 2052 | 13.936% | 22.04141 | 106.45 | 2.84 |
Label | # Samples | Average | Median | 90% Line | 95% Line | 99% Line | Min | Max | Error % | Throughput | Received KB/sec | Sent KB/sec |
addUser | 5872 | 78 | 20 | 272 | 349 | 640 | 8 | 4037 | 0.034% | 25.3522 | 109.39 | 3.27 |
Label | # Samples | Average | Median | 90% Line | 95% Line | 99% Line | Min | Max | Error % | Throughput | Received KB/sec | Sent KB/sec |
addUser-aliyun | 4116 | 106 | 81 | 149 | 229 | 499 | 55 | 3611 | 18.829% | 18.67115 | 84.33 | 2.41 |
Label | # Samples | Average | Median | 90% Line | 95% Line | 99% Line | Min | Max | Error % | Throughput | Received KB/sec | Sent KB/sec |
addUser-aliyun | 8858 | 72 | 42 | 126 | 203 | 436 | 19 | 11207 | 0.023% | 27.69735 | 119.52 | 3.57 |
在服务器端安装并打开redis-server时,可能会有三个WARNING,用以下命令可以消掉这些警告:
echo never > /sys/kernel/mm/transparent_hugepage/enabled
明天:开始任务7
问题:无
总结:无
评论