Spring Boot添加缓存

本文详细介绍如何在项目中集成Ehcache缓存系统,包括Pom.xml依赖配置、application.yml配置、ehcache.xml文件设置、自定义缓存管理器、缓存事件监听器以及在SQL和MongoDB接口中使用@CacheResult和@CacheRemove注解。

1、Pom.xml文件

<dependency>
   <groupId>javax.cache</groupId>
   <artifactId>cache-api</artifactId>
</dependency>
<dependency>
   <groupId>org.ehcache</groupId>
   <artifactId>ehcache</artifactId>
   <version>${ehcache3.version}</version>
</dependency>

2、Config/application.yml 添加配置
项目名称下的配置

cache:
  jcache.config: classpath:ehcache.xml

3、resources/ehcache.xml创建文件,添加内容

<config
        xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
        xmlns='http://www.ehcache.org/v3'
        xmlns:jsr107='http://www.ehcache.org/v3/jsr107'>

    <service>
        <jsr107:defaults enable-statistics="true">
        </jsr107:defaults>
    </service>
##缓存名称  --可注释本行
    <cache alias="csid" uses-template="heap-cache">
        <expiry><ttl unit="seconds">120</ttl></expiry>
    </cache>

    <cache alias="faceMember" uses-template="heap-cache">
        <expiry><ttl unit="hours">1</ttl></expiry>
        <heap>5000</heap>
    </cache>

    <cache-template name="heap-cache">
        <listeners>
            <listener>
                <class>com.wiwide.tpapi.server.config.CacheEventLogger</class>
                <event-firing-mode>ASYNCHRONOUS</event-firing-mode>
                <event-ordering-mode>UNORDERED</event-ordering-mode>
                <events-to-fire-on>CREATED</events-to-fire-on>
                <events-to-fire-on>UPDATED</events-to-fire-on>
                <events-to-fire-on>EXPIRED</events-to-fire-on>
                <events-to-fire-on>REMOVED</events-to-fire-on>
                <events-to-fire-on>EVICTED</events-to-fire-on>
            </listener>
        </listeners>
        <resources>
            <heap unit="entries">1000</heap>
            <offheap unit="MB">100</offheap>
        </resources>
    </cache-template>
</config>

4、读取配置的类

package ….config; 简化

import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.concurrent.ConcurrentMapCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableCaching
public class CacheConfiguration {

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

5、创建缓存的日志类

package com.wiwide.tpapi.server.config;

import lombok.extern.slf4j.Slf4j;
import org.ehcache.event.CacheEvent;
import org.ehcache.event.CacheEventListener;

@Slf4j
public class CacheEventLogger implements CacheEventListener<Object, Object> {

  @Override
  public void onEvent(CacheEvent<?, ?> event) {
    String template = "CacheEvent: %s, Key: %s, OldValue: %s, NewValue: %s";
    log.trace(String.format(template,
        event.getType(), event.getKey(), event.getOldValue(), event.getNewValue()));
  }
}


6、sql接口类中添加查询添加缓存和删除移除缓存配置
操作MySQL

@CacheResult(cacheName = "csid")
@Select("<script>"
    + "select mapping_id from shop_mapping_g "
    + "where business_key = #{bkey} and shop_id = #{shop_id} and mapping_type = '' "
    + "</script>")
String getCsid(
    @Param("bkey") int bkey,
    @Param("shop_id") int shopId);

@CacheRemove(cacheName = "csid")
@Insert("<script>"
    + "insert into shop_mapping_g "
    + "  (shop_id, business_key, client_id, mapping_type, mapping_id) "
    + "  values "
    + "  (#{shop_id}, #{bkey}, '', '', #{mapping_id}) "
    + "on duplicate key update mapping_id = #{mapping_id} "
    + "</script>")
int upsertShopMapping(
    @Param("bkey") int bkey,
    @Param("shop_id") int shopId,
    @Param("mapping_id") @CacheValue String mappingId);

@CacheRemove(cacheName = "csid")
@Delete("<script>"
    + "delete from shop_mapping_g where business_key = #{bkey} and shop_id = #{shop_id} "
    + "</script>")
int deleteShopMapping(
    @Param("bkey") int bkey,
    @Param("shop_id") int shopId);

7、MongoDB接口中添加查询添加缓存和删除移除缓存配置
操作MongoDB


package com.wiwide.tpapi.server.visioncenter.domain;

import com.wiwide.tpapi.server.config.cache.MemberInfoCacheKeyGenerator;
import javax.cache.annotation.CacheRemove;
import javax.cache.annotation.CacheResult;
import org.springframework.data.mongodb.repository.MongoRepository;

public interface MemberInfoRepository extends MongoRepository<MemberInfo, String> {

  MemberInfo findByBusinessKeyAndMemberId(int businessKey, String memId);

  @CacheResult(cacheName = "faceMember", cacheKeyGenerator = MemberInfoCacheKeyGenerator.class)
  MemberInfo findTop1ByMemberPersonFaceid(String faceid);

  @CacheRemove(cacheName = "faceMember", cacheKeyGenerator = MemberInfoCacheKeyGenerator.class)
  <S extends MemberInfo> S save(S entity);

  @CacheRemove(cacheName = "faceMember", cacheKeyGenerator = MemberInfoCacheKeyGenerator.class)
  void delete(MemberInfo entity);
}



package com.wiwide.tpapi.server.config.cache;

import com.wiwide.tpapi.server.visioncenter.domain.MemberInfo;
import java.lang.annotation.Annotation;
import javax.cache.annotation.CacheInvocationParameter;
import javax.cache.annotation.CacheKeyGenerator;
import javax.cache.annotation.CacheKeyInvocationContext;
import javax.cache.annotation.GeneratedCacheKey;
import lombok.Data;
import lombok.val;

public class MemberInfoCacheKeyGenerator implements CacheKeyGenerator {

  @Override
  public GeneratedCacheKey generateCacheKey(
      CacheKeyInvocationContext<? extends Annotation> cacheKeyInvocationContext) {

    if (1 != cacheKeyInvocationContext.getKeyParameters().length) {
      return null;
    }

    CacheInvocationParameter keyParameter = cacheKeyInvocationContext.getKeyParameters()[0];
    Object value = keyParameter.getValue();

    String faceid;

    if (value instanceof MemberInfo) {
      // MemberInfo for save/update/delete
      val member = (MemberInfo)value;
      if (null == member.getMember() || null == member.getMember().getPerson()) {
        return null;
      }

      faceid = member.getMember().getPerson().getFaceid();
    } else if (value instanceof String) {
      // String(faceid) for query
      faceid = (String)value;
    } else {
      // Unsupported
      String msg = String.format("Cache key type wrong. Required %s or String, found %s.",
          MemberInfo.class.getName(), value.getClass().getName());
      throw new ClassCastException(msg);
    }

    return new MemberInfoFaceIdKey(faceid);
  }

  @Data
  private static class MemberInfoFaceIdKey implements GeneratedCacheKey {

    private String faceid;

    MemberInfoFaceIdKey(String faceid) {
      this.faceid = faceid;
    }
  }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值