Ehcache的简单使用

1.使用场景:
高频次访问
数据时效性要求不高
数据获取比较难(经过一定的计算)

2.使用的意义:
提高反馈速度
节省计算资源(当然,这个一般比较次要)

上例子

1.类路径下添加ehcache.xml配置文件
2.添加缓存管理器(采用注解的方式)
3.在被应用的方法上使用@Cacheable即可,当然Ehcache的注解比较多这里不做过多讲解
代码如下:
package com.didi.controller;

import net.sf.ehcache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.cache.ehcache.EhCacheManagerFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;

@Configuration
@EnableCaching
public class CachingConfig {

@Bean
public EhCacheCacheManager cacheManager(CacheManager cm){
    return new EhCacheCacheManager(cm);
}

@Bean
public EhCacheManagerFactoryBean ehcache(){
    EhCacheManagerFactoryBean ehCacheManagerFactoryBean = new EhCacheManagerFactoryBean();
    ehCacheManagerFactoryBean.setConfigLocation(new ClassPathResource("ehcache.xml"));
    return ehCacheManagerFactoryBean;
}

}

package com.didi.controller;

import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
@Cacheable(“tasks”)
public class HelloService {

public String hello(int num){
    System.out.println("没走缓存");
    return "没走缓存";
}

}

编辑器没弄明白,配置文件没copy过来,可以随便在网上找个
ehcache xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
xsi:noNamespaceSchemaLocation=”ehcache.xsd”>

<cache name="tasks"
       maxEntriesLocalHeap="200"
       timeToLiveSeconds="600">
</cache>

package com.didi.controller;

import com.didi.SpringUtils;
import com.didi.domain.Man;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.inject.Inject;

@RestController
@Component
public class AopController {

/* @Inject
private SendEmailService sendEmailService;*/
@Inject
private HelloService helloService;

@RequestMapping("mail")
public String mail(){
    System.out.println("可以成功访问-----------");
    String result = helloService.hello(1);
    System.out.println("获取结果" + result);
    return "成功调用mail方法";
}

}

测试:
访问http://localhost:8080/mail
结果:
可以成功访问———–
没走缓存
获取结果没走缓存
可以成功访问———–
获取结果没走缓存

说明及原理:
第二次访问,没进入方法,这说明数据被缓存了,
Spring的缓存通过AOP的机制来实现,Spring将缓存实现为一个切面,每次访问先去缓存中取,取不到在进方法

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值