1. 程式人生 > >spring的註解式cache使用

spring的註解式cache使用

基於spring的cache基本配置與使用

spring的配置檔案:

<!-- redis配置 -->
<bean id="sysConfigJedisConnFactory"
        class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
        p:use-pool="true">
        <property name="poolConfig" ref="jedisPoolConfig" />
        <property
name="hostName" value="${redis.machine.ip}" />
<property name="port" value="${redis.machine.port}" /> </bean> <bean id="sysConfigRedisTemplate" class="org.springframework.data.redis.core.RedisTemplate" p:connection-factory-ref="sysConfigJedisConnFactory" /> <!-- 配置使用快取 -->
<bean class="org.springframework.beans.factory.config.FieldRetrievingFactoryBean" id="com.leo.util.Constants.SYSCONFIG_CACHE_IN_REDIS" /> <bean id="sysConfigCacheManager" class="org.springframework.cache.support.SimpleCacheManager"> <property name="caches"
>
<set> <!-- 自定義類(實現cache介面) --> <bean class="com.leo.system.cache.SysConfigSimpleRedisCache" p:name-ref="com.leo.util.Constants.SYSCONFIG_CACHE_IN_REDIS" /> </set> </property> </bean>

自定義一個類實現spring包下的cache介面,cache註解主要是根據相應的實現方法去執行相應的操作
比如@CacheEvict註解式會執行evict方法重新整理對應hashkey中的資料儲存

/*
 * Filename SimpleRedisCache.java
 * Company  上海韻達快運總部。
 * @author  zhangFeng
 * @version 1.0.0
 */
package com.leo.manage.system.cache;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.cache.Cache;
import org.springframework.cache.support.SimpleValueWrapper;
import org.springframework.data.redis.core.RedisTemplate;

import com.leo.util.Constants;

/**
 * 註解快取REDIS簡單實現。<br>
 * K-V方式快取
 *
 * @author leo
 * @since 1.0.0_2017年1月20日
 */
public class SysConfigSimpleRedisCache implements Cache {

    Logger logger = Logger.getLogger(getClass());

    @Resource(name="sysConfigRedisTemplate")
    private RedisTemplate<Object, Object> sysConfigRedisTemplate;
    private String name;
    private int expire = -1;
    private static final String CACHE_KEY = Constants.SYSCONFIG_CACHE_IN_REDIS;

    public SysConfigSimpleRedisCache() {}

    public SysConfigSimpleRedisCache(String name, int expire) {
        super();
        this.name = name;
        this.expire = expire;
    }

    public SysConfigSimpleRedisCache(String name) {
        super();
        this.name = name;
    }

    @Override
    public String getName() {
        return this.name;
    }

    @Override
    public Object getNativeCache() {
        return null;
    }

    @Override
    public ValueWrapper get(final Object key) {
        long s = System.currentTimeMillis();
        Object object = null;
        if (key == null) {
            return null;
        }
        if(logger.isDebugEnabled()){
            logger.debug("get key: " + key);
        }
        try {
            object = sysConfigRedisTemplate.opsForHash().get(CACHE_KEY, key);
        } catch (Exception e) {
            // 此處異常無丟擲的途徑
            logger.warn("[SysConfigSimpleRedisCache.get ValueWrapper]操作異常", e);
        }
        if (logger.isInfoEnabled()) {
            logger.info(key + ">redis-get ValueWrapper 處理時間" + (System.currentTimeMillis() - s));
        }
        return object == null ? null : new SimpleValueWrapper(object);
    }

    @Override
    public void put(final Object key, final Object value) {
        try {
            if (value == null) {
                return;
            }
            if (expire > 0) {
                logger.warn("SysConfigSimpleRedisCache.put未實現[expire]!");
            } else {
                sysConfigRedisTemplate.opsForHash().put(CACHE_KEY, key, value);
            }
        } catch (Exception e) {
            // 此處異常無丟擲的途徑
            logger.warn("[put]操作異常", e);
        }
    }

    @Override
    public void evict(final Object key) {
        try {
            if (key == null) {
                return;
            }
            sysConfigRedisTemplate.opsForHash().delete(CACHE_KEY, key);
            if(logger.isDebugEnabled()) {
                logger.debug("SysConfigSimpleRedisCache evict successfully: " + key);
            }
        } catch (Exception e) {
            // 此處異常無丟擲的途徑
            logger.warn("[evict]操作異常", e);
        }

    }

    @Override
    public void clear() {
        try {
            sysConfigRedisTemplate.delete(getName());
            if(logger.isDebugEnabled()) {
                logger.debug("SysConfigSimpleRedisCache clear successfully");
            }
        } catch (Exception e) {
            // 此處異常無丟擲的途徑
            logger.warn("[clear]操作異常", e);
        }
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getExpire() {
        return expire;
    }

    public void setExpire(int expire) {
        this.expire = expire;
    }

    @SuppressWarnings("unchecked")
    @Override
    public <T> T get(final Object key, Class<T> type) {
        long s = System.currentTimeMillis();
        if (key == null) {
            return null;
        }
        Object object = null;
        try {
            object = sysConfigRedisTemplate.opsForHash().get(CACHE_KEY, key);
        } catch (Exception e) {
            // 此處異常無丟擲的途徑
            logger.warn("[SysConfigSimpleRedisCache.get <T>]操作異常", e);
        }
        if (logger.isInfoEnabled()) {
            logger.info(key + ">redis-get <T> 處理時間" + (System.currentTimeMillis() - s));
        }
        return object == null ? null : ((T) object);
    }

}

對應方法上通過註解操作:

package com.leo.system.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.leo.member.manage.system.dao.MBMNG_system_configDao;
import com.leo.member.manage.system.service.MBMNG_system_configCacheService;
import com.leo.util.Constants;

/**
 * 系統快取配置
 * @author leo
 * @since 3.5.6_2017年1月22日
 */
@Service(value = "configCacheService")
public class configCacheServiceImpl implements
        configCacheService {

    @Autowired
    private configDao dataDao;

    /**
     *  Cacheable註解,先從redis獲取資料,取不到在從資料庫獲取
     *  資料庫獲取之後把值放入redis中,對應的hashkey中的key通過key引數設定
     * 
     * 通過key獲取系統配置
     */
    @Cacheable(value = {Constants.SYSCONFIG_CACHE_IN_REDIS}, key = "'[email protected]'.concat(#sysCodeTxt != null? #sysCodeTxt : '')")
    @Override
    public String getSysValTxt(String sysCodeTxt) throws Exception {

        return dataDao.getSysValTxt(sysCodeTxt);
    }

    /**
     *  Cacheable註解,先從redis獲取資料,取不到在從資料庫獲取
     *  資料庫獲取之後把值放入redis中,對應的hashkey中的key通過key引數設定
     * 
     *  通過key獲取系統配置中json資料裡面jsonkey的值
     *  sysCodeTxt 系統配置key
     *  jsonKey 系統配置key對應的json資料裡面的jsonkey
     */
    @Cacheable(value = {Constants.SYSCONFIG_CACHE_IN_REDIS},key = "'[email protected]'.concat(#sysCodeTxt != null? #sysCodeTxt : '').concat('@').concat(#jsonKey != null? #jsonKey : '')")
    @Override
    public String getSysValTxtJsonkey(String sysCodeTxt, String jsonKey) throws Exception {
        String sysValTxt = dataDao.getSysValTxt(sysCodeTxt);
        JSONObject parseObject = JSON.parseObject(sysValTxt);
        return parseObject.getString(jsonKey);
    }

    /**
     * 修改資料 
     * 修改資料時,先執行程式碼體的操作,然後會根據hashkey(Constants.SYSCONFIG_CACHE_IN_REDIS)清除redis的值
     * allEntries 表示清除所有實體
     */
    @CacheEvict(value = { Constants.SYSCONFIG_CACHE_IN_REDIS }, allEntries = true)
    @Override
    public void updateData(configVO vo,
            RuntimeOperator operateInf) {
        // TODO
        configPO po = vo.toPO();
        Object[] keys = po.getKeys();
        configPO po0 = dataDao.getSingle(keys);
        if (po0 == null) {
            throw new ServiceException(ErrorCode.ERROR_RECORD_NOT_EXISTS);
        }

        po.setUpdate_time(Timestamp.valueOf(operateInf.getOperate_tm()));

        dataDao.update(po);

    }
}

相關推薦

spring註解cache使用

基於spring的cache基本配置與使用 spring的配置檔案: <!-- redis配置 --> <bean id="sysConfigJedisConnFactory" class="org.springframew

spring註解引數校驗

一般入參我們都會轉為vo物件。那麼直接在物件的屬性上註解即可。 其實spring用的是hibernate的validator. 步驟 1.配置spring.xml <mvc:annotation-driven /> 2.配置

關於Spring註解事務@Transactional的簡單描述

一、背景: 目前很多專案的事務處理都是利用Spring的註解式事務實現的(@Transactional)。 在測試事務回滾的過程中發現如下現象: throw new RuntimeException("xxxxxxxxxxxx"); 事務回滾 throw new

Spring註解事物不起作用的原因分析

1、首先檢查配置檔案是否正確:<!-- 事物管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionM

Spring註解實務@Transactional註解引數詳解

spring事務一般由AOP統一處理,但當用tx:annotation-driven進行事務管理時,就需要藉助@Transactional 事物註解方式: @Transactional 當標於類前時, 標示類中所有方法都進行事物處理 , 例子: @Service @Tra

SPRING CACHE REDIS 註解實現快取策略

為了解決資料庫查詢效率瓶頸,提升併發系統能力,快取的應用已經非常普遍和必要了。剛接觸REDIS時,如何使SPRING框架與REDIS更高效地整合,困擾了我很長時間。 先說下不使用SPRING CACHE時的兩種快取應用模式: 1.使用redis作為持久層的二級快

Spring MVC 使用介紹(七)—— 註解控制器(三)

處理 分隔 arr color ref 內容 例如 生產者 value 一、MIME類型 MIME類型格式:type/subtype(;parameter)? type:主類型,任意的字符串,如text,如果是*號代表所有 subtype:子類型,任意的字符串,如html

第十二講:12,spring宣告事務管理-註解

1,複製專案spring404 ,改名spring404-3。修改BankServiceImpl類,添加註解,package com.cruise.service.impl;import org.springframework.transaction.annotation.Tra

手寫Spring註解事務(利用AOP技術 + 註解 + Spring程式設計事務)

1.參考下面的文章搭建一個無事務管理的SSM操作資料庫的框架       Spring 使用Druid資料來源 整合 Mybatis 2.AOP技術參考       AOP技術應用實現 3.第一步首先實現Sprin

spring-framework-4.1.6 mvc整合commons-dbutils-1.6註解事務

dbutils 是 Apache 提供的一個開源 JDBC 工具類庫,對 JDBC 做了一些簡單的封裝,使用非常方便。在專案中經常會有用到事務,我們就來看看spring mvc是怎麼結合dbutils開發註解式事務的。 1、下載commons-dbutils-1.6.jar

Spring Transaction 5.1.3 原始碼分析 : AnnotationTransactionAttributeSource 解析註解事務屬性

概述 Spring支援使用註解指定服務方法的事務屬性。這些事務註解可以用在類上,也可以用在方法上,如下例子所示 。 Spring事務註解例子–應用在類級別 將事務註解標記到服務元件類級別,相當於為該服務元件的每個服務方法都應用了這個註解。 import org.sprin

Spring AOP 註解和方法規則攔截

AOP 面向切面程式設計,Spring AOP  的存在是為了解耦, AOP 可以讓一組類共享相同的行為.在 OOP 只能通過繼承類和實現介面,來使程式碼的耦合度增加,且類整合只能為單繼承,阻礙更多行為新增到同一類上, AOP 彌補了 OOP 的不足. Spring 支援

spring宣告事務管理:基於註解的方式

1)在spring.xml中配置事務管理器DataSourceTransactionManager,<bean id="txManager" class="org.springframework.

Spring 3 AOP總結 (包含註解AOP定義, poincut及advice的一些定義方式)

概念 AOP(Aspect Oriented Programming),即面向切面程式設計(也叫面向方面程式設計,面向方法程式設計)。其主要作用是,在不修改原始碼的情況下給某個或者一組操作新增額外的功能。像日誌記錄,事務處理,許可權控制等功能,都可以用AOP來“優雅”地實現,使這些額外功能和真正的業務邏

struts,spring和Hibernate整合(註解

首先編寫可持久化的實體@Entity @Table(name = "Stock") public class Stock { @Id //標識實體中ID和底層資料表的主鍵統一 @GeneratedValue private int id; //

spring 註解 事務和宣告事務共存的情況下如何決定先後順序

首先先看配置檔案: [html] view plain copy print?<!– hibernate –>    <beanid=“sessionFactory”        class=“org.springframework.orm.hibernate3.LocalSessi

dubbo+zookeeper+spring整合(註解demo)

最近整理了一下dubbo+zookeeper+spring的主解式開發,做了一個小的demo, 環境: 1)     本地zookeeper 2)     本地dubbo 3)     Jkd1.8 4)     Eclipse 5)    Tomcat8 一:單機模式

spring整合quartz任務排程(註解

配置springmvc.xml xmlns 多加下面的內容、 xmlns:task="http://www.springframework.org/schema/task" 然後xsi:schemaLocation多加下面的內容、 http://w

spring 宣告事務管理註解方式實現

使用註解實現Spring的宣告式事務管理,更加簡單! 步驟:          1) 必須引入Aop相關的jar檔案          2) bean.xml中指定註解方式實現宣告式事務管理以及應用的事務管理器類          3)在需要新增事務控制的地方,寫上: @T

spring事務 只需要datasource 就可以的註解配置

spring事務 註解式配置只需要datasource 就可以 <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http: