spring 缓存 spring cache 介绍和简单实现

 我们知道缓存对于提高系统的性能有着非常重要的影响,spring在3.*的版本之后集成了cache技术,并且是基于annotation的实现,使用起来还是非常方便的。这里只是对spring cache做一个简单的了解。

业务层实现如下:

@Service
public class BookService {

	@Resource
	private BookMapper bookMapper;
	
	@Cacheable(value="books")
	public List<Book> listBooks(){
		return this.bookMapper.findAll();
	}
}

如图所示:方法上添加:@Cacheable(value="books")

application.xml

<cache:annotation-driven/>
     
      <bean  class="org.springframework.cache.support.SimpleCacheManager" id="cacheManager">
        <property name="caches">
           <set>
              <bean class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean"
               p:name="books"/>
              
           </set>
        </property>
    </bean>

测试类:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/beans.xml")
public class MyTest {

	@Resource
	private BookService bookService;
	@Test
	public void test() {
		System.out.println("---------------------");
		List<Book> list= this.bookService.listBooks();
		for(Book book : list) {
			System.out.println(book);
		}
		System.out.println("========================");
		List<Book> list1= this.bookService.listBooks();
		for(Book book : list1) {
			System.out.println(book);
		}
	}

}

输出结果:

 从输出我们可以看出,第一次会创建seesion并查询数据库,而第二次直接输出!!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值