在Spring中,我们可以使用AOP(面向切面编程)来实现缓存策略。这里是一个简单的例子,展示了如何使用Spring AOP实现缓存策略:
首先,添加Spring AOP和Cache依赖。在pom.xml文件中添加以下依赖: <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId></dependency><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId></dependency>创建一个自定义注解,用于标记需要缓存的方法。例如,创建一个名为Cacheable的注解:@Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)public @interface Cacheable { String value() default "";}创建一个切面类,用于处理自定义注解Cacheable。在这个类中,我们将实现缓存逻辑:@Aspect@Componentpublic class CacheAspect { private final Map<String, Object> cache = new ConcurrentHashMap<>(); @Around("@annotation(cacheable)") public Object handleCacheable(ProceedingJoinPoint joinPoint, Cacheable cacheable) throws Throwable { String key = generateKey(joinPoint, cacheable); if (cache.containsKey(key)) { System.out.println("Cache hit: " + key); return cache.get(key); } else { System.out.println("Cache miss: " + key); Object result = joinPoint.proceed(); cache.put(key, result); return result; } } private String generateKey(ProceedingJoinPoint joinPoint, Cacheable cacheable) { StringBuilder keyBuilder = new StringBuilder(); keyBuilder.append(joinPoint.getSignature().toShortString()); keyBuilder.append(Arrays.toString(joinPoint.getArgs())); return keyBuilder.toString(); }}在需要缓存的方法上使用@Cacheable注解:@Servicepublic class MyService { @Cacheable public String getData(String param) { // 模拟耗时操作 try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } return "Data from slow operation with param: " + param; }}现在,当你调用MyService类的getData方法时,它会被缓存。如果缓存中已经存在相同参数的结果,那么将直接从缓存中获取结果,而不是重新执行方法。这样可以提高性能,特别是在处理耗时操作时。


