spring缓存(一)--内存缓存

本文介绍了Spring Cache的基础知识,重点讲解了如何配置和使用内存缓存,即ConcurrentHashMap。内容包括通过XML和Java注解两种方式进行缓存配置,以及@Cacheable、@CachePut和@CacheEvict注解的详细用法,用于数据的缓存、更新和删除操作。
摘要由CSDN通过智能技术生成

一、简介

在开发过程中,往往需要对数据进行缓存。spring cache是spring的缓存管理方式,

默认的缓存实现是org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean,

其实也就是ConcurrentHashMap,也就是内存缓存。对数据量少且访问频繁的数据,可以采用这种方法进行数据缓存。

本文主要以默认缓存实现为例进行介绍。

二、缓存配置添加

缓存配置添加有两种,即xml方式和java注解方式,java注解方式与xml方式的内容是一样的,只是形式变了,同学们可二选一,

1、xml配置方式如下:

a) 在配置文件中添加注解驱动的配置,即

<cache:annotation-driven />
b)添加缓存管理器,内部定义缓存实现方式,可指定多个,每种缓存方式可自定义名称,如

<bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager">
    <property name="caches">
        <set>
            <bean class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean" p:name="default" />
            <bean class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean" p:name="mycache" />
        </set>
    </property>
</bean>

xml完整的配置如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:cache="http://www.springframework.org/schema/cache"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/cache
       http://www.springframework.org/schema/cache/spring-cache.xsd
        ">
    <context:component-scan base-package="com.dragon.study" />
    <cache:annotation-driven />

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值