其他分享
首页 > 其他分享> > 缓存cache介绍

缓存cache介绍

作者:互联网

1.  为何要用缓存、缓存的目的是为了什么?(https://my.oschina.net/u/3378039/blog/2986697
 一个程序的瓶颈在于数据库,内存的速度远远大于硬盘的速度,当我们一次又一次请求数据库或远程服务时会导致大量的时间耗费在数据库操作或远程方法调用上,以致于 程序性能恶化,使用数据缓存可以解决此问题。

下面是常用的缓存管理器以及可用注解方式实现缓存机制的集中类型

 2.@Cacheable/@CachePut/@CacheEvict/@Caching介绍(https://blog.csdn.net/wjacketcn/article/details/50945887

具体介绍参见链接。

其中cacheable的源码如下:

 1 public @interface Cacheable {
 2 
 3     /**
 4      * 设定要使用的cache的名字,必须提前定义好缓存
 5      */
 6     @AliasFor("cacheNames")
 7     String[] value() default {};
 8 
 9     /**
10      * 同value(),决定要使用那个/些缓存
11      */
12     @AliasFor("value")
13     String[] cacheNames() default {};
14 
15     /**
16      * 使用SpEL表达式来设定缓存的key,如果不设置默认方法上所有参数都会作为key的一部分
17      */
18     String key() default "";
19 
20     /**
21      * 用来生成key,与key()不可以共用
22      */
23     String keyGenerator() default "";
24 
25     /**
26      * 设定要使用的cacheManager,必须先设置好cacheManager的bean,这是使用该bean的名字
27      */
28     String cacheManager() default "";
29 
30     /**
31      * 使用cacheResolver来设定使用的缓存,用法同cacheManager,但是与cacheManager不可以同时使用
32      */
33     String cacheResolver() default "";
34 
35     /**
36      * 使用SpEL表达式设定出发缓存的条件,在方法执行前生效
37      */
38     String condition() default "";
39 
40     /**
41      * 使用SpEL设置出发缓存的条件,这里是方法执行完生效,所以条件中可以有方法执行后的value
42      */
43     String unless() default "";
44 
45     /**
46      * 用于同步的,在缓存失效(过期不存在等各种原因)的时候,如果多个线程同时访问被标注的方法
47      * 则只允许一个线程通过去执行方法
48      */
49     boolean sync() default false;
50 
51 }

(下图来源于https://www.cnblogs.com/psy-code/p/9537830.html

3.使用guava和caffeine缓存(据说spring5开始已经开始用caffeine替换guava)。

以下图列举集中常用的缓存的性能比较柱状图,来源于(https://blog.csdn.net/qq_35981283/article/details/82354081#commentBox

 

下面主要以guava和caffeine为例,代码如下:

a.使用guava的情景,代码如下(参考网址https://blog.csdn.net/chinabestchina/article/details/78009220):

 application-guava.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:cache="http://www.springframework.org/schema/cache"
 4        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd">
 5       <cache:annotation-driven/>
 6     <bean id="cacheManager" class="org.springframework.cache.guava.GuavaCacheManager">
 7         <property name="cacheSpecification" value="concurrencyLevel=4,expireAfterAccess=100s,expireAfterWrite=100s" />
 8         <property name="cacheNames">
 9             <list>
10                 <value>guavaCache</value>
11             </list>
12         </property>
13     </bean>
14 </beans>
 1 package com.alice.bean;
 2 
 3 public class Student {
 4     public Integer id;
 5     public String name;
 6 
 7     public Integer getId() {
 8         return id;
 9     }
10 
11     public void setId(Integer id) {
12         this.id = id;
13     }
14 
15     public String getName() {
16         return name;
17     }
18 
19     public void setName(String name) {
20         this.name = name;
21     }
22 }
 1 package com.alice.guava;
 2 
 3 import com.alice.bean.Student;
 4 
 5 public interface StudentService {
 6     public Student getStudent(Integer id);
 7 
 8     public Student updateStudent(Student stu);
 9 
10     public void deleteStudent(Integer id);
11 
12     public void deleteAllStudent();
13 
14     public void myDelete(Integer id);
15 }
 1 package com.alice.guava;
 2 
 3 import com.alice.bean.Student;
 4 import org.springframework.aop.framework.AopContext;
 5 import org.springframework.cache.annotation.CacheEvict;
 6 import org.springframework.cache.annotation.CachePut;
 7 import org.springframework.cache.annotation.Cacheable;
 8 import org.springframework.stereotype.Service;
 9 
10 @Service("studentGuavaCache")
11 public class StudentGuavaCacheImpl implements StudentService {
12 
13     @Cacheable(value = "guavaCache",key="'id_'+#id",condition = "#id<3")
14     public Student getStudent(Integer id) {
15         Student stu = new Student();
16         stu.setId(id);
17         stu.setName("apple");
18         return stu;
19     }
20 
21     @CachePut(value = "guavaCache",key="'id_'+#stu.getId()")
22     public Student updateStudent(Student stu){
23         System.out.println("update stu");
24         return stu;
25     }
26 
27 
28     @CacheEvict(value = "guavaCache",key="'id_'+#id")
29     public void deleteStudent(Integer id){
30 
31         System.out.println("delete student "+id);
32     }
33 
34     public void myDelete(Integer id){
35         try {
36             StudentService ss = (StudentService) AopContext.currentProxy();
37             ss.deleteStudent(id);
38             return ;
39         }catch (Exception e){
40             e.printStackTrace();
41 
42         }
43         this.deleteStudent(id);
44     }
45 
46     @CacheEvict(value = "guavaCache",allEntries = true)
47     public void deleteAllStudent(){
48 
49         System.out.println("delete all student ");
50     }
51 }
 1 package com.alice.guava;
 2 
 3 import com.alice.bean.Student;
 4 import org.springframework.context.support.ClassPathXmlApplicationContext;
 5 import org.springframework.util.Assert;
 6 
 7 public class SpringGuavaCacheMain {
 8     public static void main(String[] args) {
 9         ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("classpath:application-cache.xml","classpath:application-spring.xml","classpath:application-mybatis.xml");
10         StudentService studentService = (StudentService) ac.getBean("studentGuavaCache");
11 
12         Integer id =1;
13         Student stu = studentService.getStudent(id);  //新建缓存
14         stu = studentService.getStudent(id);   //从缓存中取
15 
16         studentService.myDelete(id);
17         stu = studentService.getStudent(id);   //从缓存中取
18 
19         stu.setName("banana");  //重新设置值
20         Student stu1 = studentService.getStudent(id);
21         stu.setName("banana");
22         studentService.updateStudent(stu); //更新缓存
23         stu = studentService.getStudent(id); //从缓存中取出新值
24 
25         stu = new Student();  //新实例
26         stu.setId(0);
27         studentService.updateStudent(stu);  //用新建的实例进行更新,会新建缓存
28         stu = studentService.getStudent(0);  //从缓存中取
29 
30         studentService.deleteStudent(id);  // 删除缓存
31         stu = studentService.getStudent(id);  //再次新建缓存
32 
33         id=2;
34         stu = studentService.getStudent(id); //新建缓存
35         studentService.deleteAllStudent(); //删除所有缓存
36         id=1;
37         stu = studentService.getStudent(id); //因所有缓存被前一步清除,会新建缓存
38 
39         id=5;
40         stu = studentService.getStudent(id); //不会新建缓存 因为设置了缓存条件必须小于3
41         stu = studentService.getStudent(id); //因没有缓存,不会从缓存中取
42 
43         Assert.notNull(stu,"deprecated");
44     }
45 }

2.使用caffeine

这里扩展了下原本的caffeineManager

 1 package com.alice.caffeine;
 2 
 3 import com.github.benmanes.caffeine.cache.Caffeine;
 4 import org.springframework.cache.caffeine.CaffeineCacheManager;
 5 
 6 import java.util.concurrent.TimeUnit;
 7 
 8 public class CaffeineCacheExtManager extends CaffeineCacheManager {
 9 
10     public CaffeineCacheExtManager(){
11         super();
12     }
13     /**
14      * Construct a CaffeineCacheExtManager managing caches with expireAfterWrite feature
15      *
16      * @param duration
17      * @param timeUnit
18      */
19     public CaffeineCacheExtManager(long duration, String timeUnit) {
20         this.setCaffeine(Caffeine.newBuilder().expireAfterWrite(duration, TimeUnit.valueOf(timeUnit.toUpperCase())));
21     }
22 
23 }

application-caffeine.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4        xmlns:cache="http://www.springframework.org/schema/cache"
 5        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd">
 6        <cache:annotation-driven/>
 7    
 8        <bean id="cacheManager" class="org.springframework.cache.caffeine.CaffeineCacheManager"/>
 9 
10        <bean id="tenSecondCacheManager" class="com.alice.caffeine.CaffeineCacheExtManager">
11               <constructor-arg name="duration" value="10"/>
12               <constructor-arg name="timeUnit" value="SECONDS"/>
13        </bean>
14 </beans>
1 package com.alice.caffeine;
2 
3 import com.alice.bean.Student;
4 
5 public interface StudentService {
6     public Student getStudent(Integer id);
7 }
 1 package com.alice.caffeine;
 2 
 3 import com.alice.bean.Student;
 4 import org.springframework.aop.framework.AopContext;
 5 import org.springframework.cache.annotation.CacheEvict;
 6 import org.springframework.cache.annotation.CachePut;
 7 import org.springframework.cache.annotation.Cacheable;
 8 import org.springframework.stereotype.Service;
 9 
10 @Service("CaffeineCache")
11 public class StudentCaffeineCacheImpl implements StudentService {
12 
13     @Cacheable(cacheManager = CacheMgmtName.TEN_SECOND_CACHE_MANAGER,cacheNames =CacheNames.QUERY_STUINFO_CACHE, key="'id_'+#id",condition = "#id<3")
14     public Student getStudent(Integer id) {
15         Student stu = new Student();
16         stu.setId(id);
17         stu.setName("apple");
18         return stu;
19     }
20 }
 1 package com.alice.caffeine;
 2 
 3 import com.alice.bean.Student;
 4 import com.alice.caffeine.StudentService;
 5 import org.springframework.context.support.ClassPathXmlApplicationContext;
 6 
 7 public class test  {
 8     public static void main(String[] args){
 9         ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("classpath:application-cache.xml","classpath:application-spring.xml","classpath:application-mybatis.xml","classpath:application-caffeine.xml");
10         StudentService studentService = (StudentService) ac.getBean("CaffeineCache");
11         int id =1;
12         Student stu = studentService.getStudent(id);
13         stu = studentService.getStudent(id);
14     }
15 }

 

标签:缓存,cache,介绍,public,stu,import,studentService,id
来源: https://www.cnblogs.com/alice-cj/p/10408618.html