package com.jiayue.ipfcst.fileupload.service; import com.jiayue.ipfcst.common.data.entity.UploadFileCode; import com.jiayue.ipfcst.common.data.repository.UploadFileCodeRepository; import net.sf.ehcache.Cache; import net.sf.ehcache.Element; import net.sf.ehcache.search.*; import net.sf.ehcache.search.Results; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.ehcache.EhCacheCacheManager; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import java.util.*; /** * 上报文件CODE码服务类 * @author xsl * @version 3.0 */ @Service public class UploadFileCodeService { @Autowired UploadFileCodeRepository uploadFileCodeRepository; @Autowired EhCacheCacheManager ehCacheCacheManager; /** * 保存CODE码 * * @param uploadFileCode CODE信息 */ @Transactional(propagation = Propagation.REQUIRED) public UploadFileCode save(UploadFileCode uploadFileCode) { uploadFileCodeRepository.save(uploadFileCode); clearFileCodeCache(); return uploadFileCode; } @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class) public void saveCloud(List beans) { if(beans != null && beans.size() > 0){ clearFileCodeCache(); uploadFileCodeRepository.deleteAll(); uploadFileCodeRepository.saveAll(beans); } } /** * 删除通道信息 * * @param uploadFileCode CODE信息 */ @Transactional(propagation = Propagation.REQUIRED) public void delete(UploadFileCode uploadFileCode) { clearFileCodeCache(); uploadFileCodeRepository.delete(uploadFileCode); } /** * 移除缓存中的CODE信息 */ public void clearFileCodeCache() { List uploadFileCodeList = this.get(); Cache cache = ehCacheCacheManager.getCacheManager().getCache("searchablecache"); for (UploadFileCode uploadFileCode : uploadFileCodeList) { cache.remove("code" + uploadFileCode.getId()); } } /** * 查询通道信息 * * @return 通道信息 */ public List get() { Cache cache = ehCacheCacheManager.getCacheManager().getCache("searchablecache"); Query query = cache.createQuery(); //查询结果中包含Key和value query.includeKeys().includeValues(); Attribute keyName = cache.getSearchAttribute("key"); query.addCriteria(keyName.ilike("*code*")); Results results = query.execute(); List resultList = results.all(); List list = new ArrayList(); if (resultList != null && !resultList.isEmpty()) { for (Result result : resultList) { UploadFileCode e = (UploadFileCode) result.getValue(); list.add(e); } results.discard(); } else { //查询数据库 list = uploadFileCodeRepository.findAll(); for (UploadFileCode uploadFileCode : list) { //将结果存入缓存 cache.put(new Element("code" + uploadFileCode.getId(), uploadFileCode)); } } return list; } }