Spring缓存注解@Cache,@CachePut , @CacheEvict,@CacheConfig使用

转自:http://blog.csdn.net/sanjay_f/article/details/47372967

@Cacheable、@CachePut、@CacheEvict 注释介绍

表 1. @Cacheable 作用和配置方法
@Cacheable 的作用 主要针对方法配置,能够根据方法的请求参数对其结果进行缓存
@Cacheable 主要的参数
value 缓存的名称,在 spring 配置文件中定义,必须指定至少一个 例如:
@Cacheable(value=”mycache”) 或者 
@Cacheable(value={”cache1”,”cache2”}
key 缓存的 key,可以为空,如果指定要按照 SpEL 表达式编写,如果不指定,则缺省按照方法的所有参数进行组合 例如:
@Cacheable(value=”testcache”,key=”#userName”)
condition 缓存的条件,可以为空,使用 SpEL 编写,返回 true 或者 false,只有为 true 才进行缓存 例如:
@Cacheable(value=”testcache”,condition=”#userName.length()>2”)
------------------------------------------------------------
--
表 2. @CachePut 作用和配置方法
@CachePut 的作用 主要针对方法配置,能够根据方法的请求参数对其结果进行缓存,和 @Cacheable 不同的是,它每次都会触发真实方法的调用
@CachePut 主要的参数
value 缓存的名称,在 spring 配置文件中定义,必须指定至少一个 例如:
@Cacheable(value=”mycache”) 或者 
@Cacheable(value={”cache1”,”cache2”}
key 缓存的 key,可以为空,如果指定要按照 SpEL 表达式编写,如果不指定,则缺省按照方法的所有参数进行组合 例如:
@Cacheable(value=”testcache”,key=”#userName”)
condition 缓存的条件,可以为空,使用 SpEL 编写,返回 true 或者 false,只有为 true 才进行缓存 例如:
@Cacheable(value=”testcache”,condition=”#userName.length()>2”)

//

表 3. @CacheEvict 作用和配置方法
@CachEvict 的作用 主要针对方法配置,能够根据一定的条件对缓存进行清空
@CacheEvict 主要的参数
value 缓存的名称,在 spring 配置文件中定义,必须指定至少一个 例如:
@CachEvict(value=”mycache”) 或者 
@CachEvict(value={”cache1”,”cache2”}
key 缓存的 key,可以为空,如果指定要按照 SpEL 表达式编写,如果不指定,则缺省按照方法的所有参数进行组合 例如:
@CachEvict(value=”testcache”,key=”#userName”)
condition 缓存的条件,可以为空,使用 SpEL 编写,返回 true 或者 false,只有为 true 才清空缓存 例如:
@CachEvict(value=”testcache”,
condition=”#userName.length()>2”)
allEntries 是否清空所有缓存内容,缺省为 false,如果指定为 true,则方法调用后将立即清空所有缓存 例如:
@CachEvict(value=”testcache”,allEntries=true)
beforeInvocation 是否在方法执行前就清空,缺省为 false,如果指定为 true,则在方法还没有执行的时候就清空缓存,缺省情况下,如果方法执行抛出异常,则不会清空缓存 例如:
@CachEvict(value=”testcache”,beforeInvocation=true)

--------------
额外补充 :@cache(“something");这个相当于save()操作,@cachePut相当于Update()操作,只要他标示的方法被调用,那么都会缓存起来,而@cache则是先看下有没已经缓存了,然后再选择是否执行方法。@CacheEvict相当于Delete()操作。用来清除缓存用的。

这写配置的声明需要配置好了@enableCache才有用,具体的配置可以看这篇文章
http://blog.csdn.net/sanjay_f/article/details/47363845

如果忘记了SpEL怎么用了,  do yourself a favor and read  Chapter 9, Spring Expression Language (SpEL) :

-------------
[html]  view plain  copy
  1. importorg.springframework.stereotype.Service;  
  2. importcom.springcache.annotation.Cacheable;  
  3. @Service  
  4. @Cacheable  
  5. public class MemcachedService{  
  6.   @Cacheable(name="remote",key="'USER_NAME_'+#args[0]")  
  7. public String storeUserName(String accountId,String name)  
  8. {  
  9.   return name;  
  10. }  
  11.   @Cacheable(name="remote")  
  12.  public String storeUserAddress(String accountId,String address){  
  13.    return address;  
  14.   }  
  15. }  





不知道你们注意到一个问题没有,就是所有的@Cacheable()里面都有一个name=“xxx”的属性,这显然如果方法多了,写起来也是挺累的,如果可以一次性声明完 那就省事了,
所以,有了@CacheConfig这个配置, @CacheConfig  is a class-level annotation that allows to share the cache names,不过不用担心,如果你在你的方法写别的名字,那么依然以方法的名字为准。

[html]  view plain  copy
  1. @CacheConfig("books")  
  2. public class BookRepositoryImpl implements BookRepository {  
  3.   
  4.     @Cacheable  
  5.     public Book findBook(ISBN isbn) {...}  
  6. }  


当然还有另外一个情况, @ Cacheable ( name = "remote" , key = "'USER_NAME_'+#args[0]" ,conditional=“xxx”,allEntries=true,beforeInvocation=true ) ,像这样的配置就很长,
<em><span class="hl-annotation" style="color: gray;"><span class="crayon-sy" style="font-family: inherit; white-space: pre; height: inherit; font-size: inherit !important; font-weight: inherit !important; line-height: inherit !important; color: rgb(51, 51, 51) !important;">@</span><span class="crayon-e" style="font-family: inherit; white-space: pre; height: inherit; font-size: inherit !important; font-weight: inherit !important; line-height: inherit !important; color: rgb(0, 78, 208) !important;">Cacheable</span><span class="crayon-sy" style="font-family: inherit; white-space: pre; height: inherit; font-size: inherit !important; font-weight: inherit !important; line-height: inherit !important; color: rgb(51, 51, 51) !important;">(</span><span class="crayon-v" style="font-family: inherit; white-space: pre; height: inherit; font-size: inherit !important; font-weight: inherit !important; line-height: inherit !important; color: rgb(0, 45, 122) !important;">name</span><span class="crayon-h" style="font-family: inherit; white-space: pre; height: inherit; font-size: inherit !important; font-weight: inherit !important; line-height: inherit !important; color: rgb(0, 111, 224) !important;"> </span><span class="crayon-o" style="font-family: inherit; white-space: pre; height: inherit; font-size: inherit !important; font-weight: inherit !important; line-height: inherit !important; color: rgb(0, 111, 224) !important;">=</span><span class="crayon-h" style="font-family: inherit; white-space: pre; height: inherit; font-size: inherit !important; font-weight: inherit !important; line-height: inherit !important; color: rgb(0, 111, 224) !important;"> </span><span class="crayon-s" style="font-family: inherit; white-space: pre; height: inherit; font-size: inherit !important; font-weight: inherit !important; line-height: inherit !important; color: rgb(0, 128, 0) !important;">"book"</span><span class="crayon-sy" style="font-family: inherit; white-space: pre; height: inherit; font-size: inherit !important; font-weight: inherit !important; line-height: inherit !important; color: rgb(51, 51, 51) !important;">,</span></span></em><span style="line-height: 1.4; color: gray; font-weight: inherit;"><em> key="#isbn"</em></span><span class="crayon-h" style="font-family: inherit; font-style: italic; height: inherit; font-size: inherit !important; line-height: inherit !important; font-weight: inherit !important; color: rgb(0, 111, 224) !important;">,conditional=“xxx”,<span style="color: rgb(85, 85, 85); font-size: 13px; line-height: 15.36px;">allEntries=true,<span style="line-height: 15.36px;">beforeInvocation=true</span></span></span><span class="crayon-sy" style="font-family: inherit; font-style: italic; height: inherit; font-size: inherit !important; line-height: inherit !important; font-weight: inherit !important;">) </span><em><span class="hl-annotation" style="color: gray;"><span class="crayon-h" style="font-family: inherit; white-space: pre; height: inherit; font-size: inherit !important; font-weight: inherit !important; line-height: inherit !important; color: rgb(0, 111, 224) !important;">
</span></span></em><span class="hl-keyword" style="color: rgb(127, 0, 85); font-weight: bold;">public</span> Book findBook(ISBN isbn, <span class="hl-keyword" style="color: rgb(127, 0, 85); font-weight: bold;">boolean</span> checkWarehouse, <span class="hl-keyword" style="color: rgb(127, 0, 85); font-weight: bold;">boolean</span> includeUsed)
这样的配置很长,而且有可能声明在很多个方法的,所以我们很想精简点,容易配置些。所以
<em><span class="hl-annotation" style="color: gray;">@findBookByIsbnervice</span></em>
<span class="hl-keyword" style="color: rgb(127, 0, 85); font-weight: bold;">public</span> Book findBook(ISBN isbn, <span class="hl-keyword" style="color: rgb(127, 0, 85); font-weight: bold;">boolean</span> checkWarehouse, <span class="hl-keyword" style="color: rgb(127, 0, 85); font-weight: bold;">boolean</span> includeUsed)

新建一个文件 findBookByIsbn, 内容如下
<em><span class="hl-annotation" style="color: gray;">@Retention(RetentionPolicy.RUNTIME)</span>
<span class="hl-annotation" style="color: gray;">@Target({ElementType.METHOD})</span>
<span class="hl-annotation" style="color: gray;">@Cacheable(cacheNames="books", key="#isbn")</span></em>
<span class="hl-keyword" style="font-weight: bold;">public</span> <em><span class="hl-annotation" style="color: gray;">@interface</span></em> <span style="font-style: italic; line-height: 1.4; font-weight: inherit;">findBookByIsbn</span> {
}



-------------------------------

Features summary

For those who are familiar with spring’s caching annotations, the following table describes the main differences between the Spring annotations and the JSR-107 counterpart:

Table 35.3. Spring vs. JSR-107 caching annotations

Spring JSR-107 Remark

@Cacheable

@CacheResult

Fairly similar. @CacheResult can cache specific exceptions and force the execution of the method regardless of the content of the cache.

@CachePut

@CachePut

While Spring updates the cache with the result of the method invocation, JCache requires to pass it as an argument that is annotated with @CacheValue. Due to this difference, JCache allows to update the cache before or after the actual method invocation.

@CacheEvict

@CacheRemove

Fairly similar. @CacheRemove supports a conditional evict in case the method invocation results in an exception.

@CacheEvict(allEntries=true)

@CacheRemoveAll

See @CacheRemove.

@CacheConfig

@CacheDefaults

Allows to configure the same concepts, in a similar fashion.


--------------


关于异常

JCache can manage exceptions thrown by annotated methods:

this can prevent an update of the cache but it can also cache the exception as an indicator of the failure instead of calling the method again. 

Let’s assume that InvalidIsbnNotFoundException is thrown if the structure of the ISBN is invalid.

This is a permanent failure, no book could ever be retrieved with such parameter. 

The following caches the exception so that further calls with the same,

invalid ISBN, throws the cached exception directly instead of invoking the method again.

@CacheResult(cacheName=<span class="hl-string" style="color: rgb(42, 0, 255);">"books"</span>, <span class="strong"><strong>exceptionCacheName="failures"</strong></span>
             <span class="strong"><strong>cachedExceptions = InvalidIsbnNotFoundException.class</strong></span>)
<span class="hl-keyword" style="color: rgb(127, 0, 85); font-weight: bold;">public</span> Book findBook(ISBN isbn)

//

以下部分 为个人添加部分:

添加一个例子:DictionaryContext .java


package com.location.util;


import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;


import org.apache.commons.lang.StringUtils;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;


import com.location.monitor.dao.SuperDAO;
import com.location.monitor.vo.SysDictionaryVO;
@Component
public class DictionaryContext {

//根据内容缓存数据字典
@SuppressWarnings("unchecked")
@CachePut(value="dictionaryCache", key="'dictionary_' + #table_name + '_' + #column_name")  
public synchronized List<SysDictionaryVO> setDictionary(String table_name, String column_name) {
   SuperDAO superDAO = (SuperDAO)SpringHelper.getBean("superDAO");
   //JdbcTemplate jdbcTemplate = (JdbcTemplate)SpringHelper.getBean("jdbcTemplate");
   List<SysDictionaryVO> dics = superDAO.find("from SysDictionaryVO where dr=0 and table_name=? and column_name=? ORDER BY orderby", new Object[]{table_name, column_name});
return dics;
}

//根据内容缓存数据字典
@CachePut(value="dictionaryCache", key="'dictionaryContent_' + #table_name + '_' + #column_name + '_' + #content")
public synchronized SysDictionaryVO setDictionaryContent(String table_name, String column_name, String content) {
SuperDAO superDAO = (SuperDAO)SpringHelper.getBean("superDAO");
SysDictionaryVO dic = (SysDictionaryVO)superDAO.get("from SysDictionaryVO where dr=0 and table_name=? and column_name=? and display_name =? ", new Object[]{table_name, column_name, content});
return dic;
}

//根据值缓存数据字典
@CachePut(value="dictionaryCache", key="'dictionaryValue_' + #table_name + '_' + #column_name + '_' + #value")
public synchronized SysDictionaryVO setDictionaryValue(String table_name, String column_name, String value) {
SuperDAO superDAO = (SuperDAO)SpringHelper.getBean("superDAO");
SysDictionaryVO dic = (SysDictionaryVO)superDAO.get("from SysDictionaryVO where dr=0 and table_name=? and column_name=? and value =? ", new Object[]{table_name, column_name, value});
return dic;
}

/**
* 获取数据字典
* @param table_name
* @param column_name
* @return
*/
@Cacheable(value="dictionaryCache", key="'dictionary_' + #table_name + '_' + #column_name")
public List<SysDictionaryVO> getDictionary(String table_name, String column_name){
List<SysDictionaryVO> dictionaryDomainList = setDictionary(table_name,column_name);
return dictionaryDomainList;
}

/**
* 根据数据字典值获取对应的内容
* @param table_name
* @param column_name
* @param value
* @return
*/
@Cacheable(value="dictionaryCache", key="'dictionaryValue_' + #table_name + '_' + #column_name + '_' + #value")
public String getDisplay_name(String table_name, String column_name, String value) {
return getDisplay_name(table_name, column_name, value, "");
}

/**
* 根据数据字典值获取对应的内容
* @param table_name
* @param column_name
* @param value
* @param defaultDisplayName
* @return
*/
@Cacheable(value="dictionaryCache", key="'dictionaryValue_' + #table_name + '_' + #column_name + '_' + #value + '_' + #defaultDisplayName")
public String getDisplay_name(String table_name, String column_name, String value, String defaultDisplayName) {
if(StringUtils.isEmpty(value)){
return "";
}
SysDictionaryVO dictionaryDomain = setDictionaryValue(table_name,column_name,value);
if(dictionaryDomain == null){
return defaultDisplayName;
}
return dictionaryDomain.getDisplay_name();
}



/**
* 根据数据字典内容获取对应的值
* @param table_name
* @param column_name
* @param content
* @return
*/
@Cacheable(value="dictionaryCache", key="'dictionaryContent_' + #table_name + '_' + #column_name + '_' + #content")
public String getValue(String table_name,String column_name,String content){
SysDictionaryVO dictionaryDomain = setDictionaryContent(table_name, column_name, content);
if(dictionaryDomain == null){
return "";
}
return dictionaryDomain.getValue();
}

public String getMemo(String table_name,String column_name,String value){
if(value == null || value.trim().equals("")){
return "";
}
SysDictionaryVO domain = get(table_name,column_name,value);
if(domain != null && domain.getMemo() != null){
return domain.getMemo();
}
return "";
}

public SysDictionaryVO get(String table_name,String column_name,String value){
SuperDAO superDAO = (SuperDAO)SpringHelper.getBean("superDAO");
return (SysDictionaryVO)superDAO.get("from SysDictionaryVO where dr=0 and table_name=? and column_name=? and value =? ", new Object[]{table_name, column_name, value});
}

/**
* 适用于列表,无默认值
* @param table_name
* @param column_name
* @return
*/
@Cacheable(value="dictionaryCache", key="'dictionaryOptions_' + #table_name + '_' + #column_name")
public String getOptions(String table_name, String column_name){
return getOptions(table_name,column_name,"","",null);
}
/**
* 如果mode是yes, 默认值是"---"
* @param table_name
* @param column_name
* @param mode
* @return
*/
public String getOptions(String table_name,String column_name,String mode){
return getOptions(table_name,column_name,mode,"",null);
}

public String getOptions(String table_name,String column_name,String mode,String value){
if("".equals(value)){
return getOptions(table_name,column_name,mode,"",null);
}
return getOptions(table_name,column_name,mode,value,null);
}

public String getOptions(String table_name, String column_name, String mode, String value, List<SysDictionaryVO> notViewList){
StringBuffer result = new StringBuffer() ;
if(mode != null && mode.equalsIgnoreCase("yes")){
result.append("<option value=\'\'>----</option>");
}
List<SysDictionaryVO> dictionaryDomainList = getDictionary(table_name, column_name);
if(notViewList == null){
if(dictionaryDomainList != null && dictionaryDomainList.size() > 0){
for(int i = 0 ; i < dictionaryDomainList.size() ; i++){
SysDictionaryVO tempDomain = (SysDictionaryVO)dictionaryDomainList.get(i);
if(tempDomain.getValue() != null && !tempDomain.getValue().equals("NULL")){
if(value != null && tempDomain.getValue().equals(value.trim())){
result.append("<option value=\'" + tempDomain.getValue() + "\'" + " selected=\'selected\'>");
}else {
result.append("<option value=\'" + tempDomain.getValue() + "\'>");
}
result.append(tempDomain.getDisplay_name()).append("</option>");
}
}
}
}else{
for(int i=0;i<dictionaryDomainList.size();i++){
String notView="0";//"0"表示该条数据未被使用;"1"表示该条数据已被使用
SysDictionaryVO tempDomain = (SysDictionaryVO)dictionaryDomainList.get(i);
for(int j=0;j<notViewList.size();j++){
SysDictionaryVO notViewDomain =(SysDictionaryVO)notViewList.get(j);
if(notViewDomain.getValue().equals(tempDomain.getValue())){
notView="1";//该条数据已被使用
}
}
if(notView.equals("0")){
if(tempDomain.getValue() != null && !tempDomain.getValue().equals("NULL")){
if(value != null && tempDomain.getValue().equals(value)){
result.append("<option value=\'" + tempDomain.getValue() + "\'" + " selected=\'selected\'>");
}else {
result.append("<option value=\'" + tempDomain.getValue() + "\'>");
}
result.append(tempDomain.getDisplay_name()).append("</option>");
}
}
}

}
return result.toString();
}

@SuppressWarnings({"unchecked"})
public String getOptionsByterm(String table_name,String column_name,String mode,String value,String term){
String result = "" ;
if(mode != null && mode.equalsIgnoreCase("yes")){
result = "<option value=\'\'>----</option>";
}

   SuperDAO superDAO = (SuperDAO)SpringHelper.getBean("superDAO");
   List<SysDictionaryVO> dictionary_list = superDAO.find("from SysDictionaryVO where dr=0 and table_name=? and column_name=? ORDER BY orderby", new Object[]{table_name, column_name});

List<SysDictionaryVO> list= new ArrayList<SysDictionaryVO>();
SysDictionaryVO domain = null;
for(int j=0;j<dictionary_list.size();j++){
domain=(SysDictionaryVO)dictionary_list.get(j);
if(domain.getValue().indexOf(term)!=-1){
list.add(domain);
}
}
if(list != null && list.size() > 0){
for(int i = 0 ; i < list.size() ; i++){
SysDictionaryVO tempDomain = (SysDictionaryVO)list.get(i);
if(tempDomain.getValue() != null && !tempDomain.getValue().equals("NULL")){
if(value != null && tempDomain.getValue().equals(value)){
result += "<option value=\'" + tempDomain.getValue() + "\'" + " selected=\'selected\'>" ;
}else {
result += "<option value=\'" + tempDomain.getValue() + "\'>" ;
}
result += tempDomain.getDisplay_name();
result += "</option>";
}
}
}
return result;
}

public String getRadio(String radio_name,String table_name,String column_name,String mode){
return getRadio(radio_name,table_name,column_name,mode,"");
}

public String getRadio(String radio_name,String table_name,String column_name){
return getRadio(radio_name,table_name,column_name,"","");
}

/**
* 根据给定的map对象,生成radio
* @param radio_name
* @param map
* @param value
* @return
*/
public String getRadio(String radio_name, Map<String, Object> map, String value){
StringBuffer result = new StringBuffer(); 
if(map == null || map.size() == 0){
return "";
}
Set<Entry<String, Object>> set = map.entrySet();
for (Iterator<Entry<String, Object>> iterator = set.iterator(); iterator.hasNext();) {
Entry<String, Object> entry = (Entry<String, Object>) iterator
.next();
result.append("<input type='radio' name='").append(radio_name).append("' value='").append(entry.getKey()).append("'");
if(value != null && entry.getKey().equals(value)){
result.append("checked='checked'/>");
}else {
result.append("/>");
}
result.append(entry.getValue()).append("&nbsp;");
}
return result.toString();
}

public String getRadio(String radio_name,String table_name,String column_name,String mode,String value){
String result = "" ;
List<SysDictionaryVO> dictionaryDomainList = getDictionary(table_name, column_name);
if(dictionaryDomainList != null && dictionaryDomainList.size() > 0){
for(int i = 0 ; i < dictionaryDomainList.size() ; i++){
SysDictionaryVO tempDomain = (SysDictionaryVO)dictionaryDomainList.get(i);
if(tempDomain.getValue() != null && !tempDomain.getValue().equals("NULL")){
if(value != null && tempDomain.getValue().equals(value)){
result += "<input type=\"radio\" name=\""+radio_name+"\" value=\"" + tempDomain.getValue() + "\" checked=\"checked\">"+tempDomain.getDisplay_name()+"&nbsp;" ;
}else {
if(value.equals("") && mode != null && mode.equalsIgnoreCase("no") && i==0){
result += "<input type=\"radio\" name=\""+radio_name+"\" value=\"" + tempDomain.getValue() + "\" checked=\"checked\">"+tempDomain.getDisplay_name()+"&nbsp;" ;
}else{
result += "<input type=\"radio\" name=\""+radio_name+"\" value=\"" + tempDomain.getValue() + "\">"+tempDomain.getDisplay_name()+"&nbsp;" ;
}

}
}
}
}
return result;
}


public String getCheckBox(String checkbox_name,String table_name,String column_name,String mode){
return getCheckBox(checkbox_name,table_name,column_name,mode,null);
}

public String getCheckBox(String checkbox_name,String table_name,String column_name){
return getCheckBox(checkbox_name,table_name,column_name,"",null);
}

@SuppressWarnings("rawtypes")
public String getCheckBox(String checkbox_name,String table_name,String column_name,String mode, Object checklistObject){
String result = "" ;
List checkList=new ArrayList();
if(checklistObject!=null){
checkList=(List)checklistObject;
}
List<SysDictionaryVO> dictionaryDomainList = getDictionary(table_name, column_name);
if(dictionaryDomainList != null && dictionaryDomainList.size() > 0){
for(int i = 0 ; i < dictionaryDomainList.size() ; i++){
SysDictionaryVO tempDomain = (SysDictionaryVO)dictionaryDomainList.get(i);
if(tempDomain.getValue() != null && !tempDomain.getValue().equals("NULL")){
if(!checkList.isEmpty() && checkBool(checkList,tempDomain)){
result += "<input type=\"checkbox\" name=\""+checkbox_name+"\" value=\"" + tempDomain.getValue() + "\" checked=\"checked\">"+tempDomain.getDisplay_name()+"&nbsp;" ;
}else {
if(checklistObject==null && mode != null && mode.equalsIgnoreCase("no") && i==0){
result += "<input type=\"checkbox\" name=\""+checkbox_name+"\" value=\"" + tempDomain.getValue() + "\" checked=\"checked\">"+tempDomain.getDisplay_name()+"&nbsp;" ;
}else{
result += "<input type=\"checkbox\" name=\""+checkbox_name+"\" value=\"" + tempDomain.getValue() + "\">"+tempDomain.getDisplay_name()+"&nbsp;" ;
}

}
}
}
}
return result;
}

public String getCheckBox(String checkbox_name,String table_name,String column_name,String mode,String value){
String result = "" ;
List<SysDictionaryVO> dictionaryDomainList = getDictionary(table_name, column_name);
if(dictionaryDomainList != null && dictionaryDomainList.size() > 0){
for(int i = 0 ; i < dictionaryDomainList.size() ; i++){
SysDictionaryVO tempDomain = (SysDictionaryVO)dictionaryDomainList.get(i);
if(tempDomain.getValue() != null && !tempDomain.getValue().equals("NULL")){
if(value != null && tempDomain.getValue().equals(value)){
result += "<input type=\"checkbox\" name=\""+checkbox_name+"\" value=\"" + tempDomain.getValue() + "\" checked=\"checked\">"+tempDomain.getDisplay_name()+"&nbsp;" ;
}else{
if(value==null && mode != null && mode.equalsIgnoreCase("no") && i==0){
result += "<input type=\"checkbox\" name=\""+checkbox_name+"\" value=\"" + tempDomain.getValue() + "\" checked=\"checked\">"+tempDomain.getDisplay_name()+"&nbsp;" ;
}else{
result += "<input type=\"checkbox\" name=\""+checkbox_name+"\" value=\"" + tempDomain.getValue() + "\">"+tempDomain.getDisplay_name()+"&nbsp;" ;
}

}
}
}
}
return result;
}

@SuppressWarnings("rawtypes")
public Boolean checkBool(List checkList,SysDictionaryVO tempDomain){
if(!checkList.isEmpty()){
for(int k=0;k<checkList.size();k++){
if(tempDomain.getValue().equals(checkList.get(k).toString())){
return true;
}
}
}
return false;
}

public List<String> getValues(String table_name, String column_name){
List<String> values = new ArrayList<String>();
List<SysDictionaryVO> dics = getDictionary(table_name, column_name);
for(SysDictionaryVO dic : dics){
if(StringUtils.isNotEmpty(dic.getValue())){
values.add(dic.getValue());
}
}
return values;
}
}

对应的配置文件:ehcache.xml

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">


    <!-- version 2.7.8
    The ehcache-failsafe.xml is a default configuration for ehcache, if an ehcache.xml is not configured.


    The diskStore element is optional. It must be configured if you have overflowToDisk or diskPersistent enabled
    for any cache. If it is not configured, a warning will be issues and java.io.tmpdir will be used.


    diskStore has only one attribute - "path". It is the path to the directory where .data and .index files will be created.


    If the path is a Java System Property it is replaced by its value in the
    running VM.


    The following properties are translated:
    * user.home - User's home directory
    * user.dir - User's current working directory
    * java.io.tmpdir - Default temp file path
    * ehcache.disk.store.dir - A system property you would normally specify on the command line
          e.g. java -Dehcache.disk.store.dir=/u01/myapp/diskdir ...


    Subdirectories can be specified below the property e.g. java.io.tmpdir/one


    -->
    <diskStore path="java.io.tmpdir"/>


    <!--
    Specifies a CacheManagerEventListenerFactory, be used to create a CacheManagerPeerProvider,
    which is notified when Caches are added or removed from the CacheManager.


    The attributes of CacheManagerEventListenerFactory are:
    * class - a fully qualified factory class name
    * properties - comma separated properties having meaning only to the factory.


    Sets the fully qualified class name to be registered as the CacheManager event listener.


    The events include:
    * adding a Cache
    * removing a Cache


    Callbacks to listener methods are synchronous and unsynchronized. It is the responsibility
    of the implementer to safely handle the potential performance and thread safety issues
    depending on what their listener is doing.


    If no class is specified, no listener is created. There is no default.


    <cacheManagerEventListenerFactory class="" properties=""/>
    -->


    <!--
    (Enable for distributed operation)


    Specifies a CacheManagerPeerProviderFactory which will be used to create a
    CacheManagerPeerProvider, which discovers other CacheManagers in the cluster.


    The attributes of cacheManagerPeerProviderFactory are:
    * class - a fully qualified factory class name
    * properties - comma separated properties having meaning only to the factory.


    Ehcache comes with a built-in RMI-based distribution system with two means of discovery of
    CacheManager peers participating in the cluster:
    * automatic, using a multicast group. This one automatically discovers peers and detects
      changes such as peers entering and leaving the group
    * manual, using manual rmiURL configuration. A hardcoded list of peers is provided at
      configuration time.


    Configuring Automatic Discovery:
    Automatic discovery is configured as per the following example:
    <cacheManagerPeerProviderFactory
                        class="net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory"
                        properties="peerDiscovery=automatic, multicastGroupAddress=230.0.0.1,
                                    multicastGroupPort=4446, timeToLive=32"/>


    Valid properties are:
    * peerDiscovery (mandatory) - specify "automatic"
    * multicastGroupAddress (mandatory) - specify a valid multicast group address
    * multicastGroupPort (mandatory) - specify a dedicated port for the multicast heartbeat
      traffic
    * timeToLive - specify a value between 0 and 255 which determines how far the packets will propagate.
      By convention, the restrictions are:
      0   - the same host
      1   - the same subnet
      32  - the same site
      64  - the same region
      128 - the same continent
      255 - unrestricted




    Configuring Manual Discovery:
    Manual discovery is configured as per the following example:
    <cacheManagerPeerProviderFactory class=
                          "net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory"
                          properties="peerDiscovery=manual,
                          rmiUrls=//server1:40000/sampleCache1|//server2:40000/sampleCache1
                          | //server1:40000/sampleCache2|//server2:40000/sampleCache2"/>


    Valid properties are:
    * peerDiscovery (mandatory) - specify "manual"
    * rmiUrls (mandatory) - specify a pipe separated list of rmiUrls, in the form
                            //hostname:port


    The hostname is the hostname of the remote CacheManager peer. The port is the listening
    port of the RMICacheManagerPeerListener of the remote CacheManager peer.


    <cacheManagerPeerProviderFactory
            class="net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory"
            properties="peerDiscovery=automatic,
                        multicastGroupAddress=230.0.0.1,
                        multicastGroupPort=4446, timeToLive=1"/>
    -->


    <!--
    (Enable for distributed operation)


    Specifies a CacheManagerPeerListenerFactory which will be used to create a
    CacheManagerPeerListener, which
    listens for messages from cache replicators participating in the cluster.


    The attributes of cacheManagerPeerListenerFactory are:
    class - a fully qualified factory class name
    properties - comma separated properties having meaning only to the factory.


    Ehcache comes with a built-in RMI-based distribution system. The listener component is
    RMICacheManagerPeerListener which is configured using
    RMICacheManagerPeerListenerFactory. It is configured as per the following example:


    <cacheManagerPeerListenerFactory
        class="net.sf.ehcache.distribution.RMICacheManagerPeerListenerFactory"
        properties="hostName=fully_qualified_hostname_or_ip,
                    port=40001,
                    socketTimeoutMillis=120000"/>


    All properties are optional. They are:
    * hostName - the hostName of the host the listener is running on. Specify
      where the host is multihomed and you want to control the interface over which cluster
      messages are received. Defaults to the host name of the default interface if not
      specified.
    * port - the port the listener listens on. This defaults to a free port if not specified.
    * socketTimeoutMillis - the number of ms client sockets will stay open when sending
      messages to the listener. This should be long enough for the slowest message.
      If not specified it defaults 120000ms.


    <cacheManagerPeerListenerFactory
            class="net.sf.ehcache.distribution.RMICacheManagerPeerListenerFactory"/>
    -->




    <!-- Cache configuration.


    The following attributes are required.


    name:
    Sets the name of the cache. This is used to identify the cache. It must be unique.


    maxElementsInMemory:
    Sets the maximum number of objects that will be created in memory (0 == no limit)


maxElementsOnDisk:
    Sets the maximum number of objects that will be maintained in the DiskStore
The default value is zero, meaning unlimited.


    eternal:
    Sets whether elements are eternal. If eternal,  timeouts are ignored and the
    element is never expired.


    overflowToDisk:
    Sets whether elements can overflow to disk when the in-memory cache
    has reached the maxInMemory limit.


    The following attributes are optional.


    timeToIdleSeconds:
    Sets the time to idle for an element before it expires.
    i.e. The maximum amount of time between accesses before an element expires
    Is only used if the element is not eternal.
    Optional attribute. A value of 0 means that an Element can idle for infinity.
    The default value is 0.


    timeToLiveSeconds:
    Sets the time to live for an element before it expires.
    i.e. The maximum time between creation time and when an element expires.
    Is only used if the element is not eternal.
    Optional attribute. A value of 0 means that and Element can live for infinity.
    The default value is 0.


    diskPersistent:
    Whether the disk store persists between restarts of the Virtual Machine.
    The default value is false.


    diskExpiryThreadIntervalSeconds:
    The number of seconds between runs of the disk expiry thread. The default value
    is 120 seconds.


    diskSpoolBufferSizeMB:
    This is the size to allocate the DiskStore for a spool buffer. Writes are made
    to this area and then asynchronously written to disk. The default size is 30MB.
    Each spool buffer is used only by its cache. If you get OutOfMemory errors consider
    lowering this value. To improve DiskStore performance consider increasing it. Trace level
    logging in the DiskStore will show if put back ups are occurring.


    memoryStoreEvictionPolicy:
    Policy would be enforced upon reaching the maxElementsInMemory limit. Default
    policy is Least Recently Used (specified as LRU). Other policies available -
    First In First Out (specified as FIFO) and Less Frequently Used
    (specified as LFU)


    Cache elements can also contain sub elements which take the same format of a factory class
    and properties. Defined sub-elements are:


    * cacheEventListenerFactory - Enables registration of listeners for cache events, such as
      put, remove, update, and expire.


    * bootstrapCacheLoaderFactory - Specifies a BootstrapCacheLoader, which is called by a
      cache on initialisation to prepopulate itself.


    Each cache that will be distributed needs to set a cache event listener which replicates
    messages to the other CacheManager peers. For the built-in RMI implementation this is done
    by adding a cacheEventListenerFactory element of type RMICacheReplicatorFactory to each
    distributed cache's configuration as per the following example:


    <cacheEventListenerFactory class="net.sf.ehcache.distribution.RMICacheReplicatorFactory"
         properties="replicateAsynchronously=true,
         replicatePuts=true,
         replicateUpdates=true,
         replicateUpdatesViaCopy=true,
         replicateRemovals=true "/>


    The RMICacheReplicatorFactory recognises the following properties:


    * replicatePuts=true|false - whether new elements placed in a cache are
      replicated to others. Defaults to true.


    * replicateUpdates=true|false - whether new elements which override an
      element already existing with the same key are replicated. Defaults to true.


    * replicateRemovals=true - whether element removals are replicated. Defaults to true.


    * replicateAsynchronously=true | false - whether replications are
      asynchronous (true) or synchronous (false). Defaults to true.


    * replicateUpdatesViaCopy=true | false - whether the new elements are
      copied to other caches (true), or whether a remove message is sent. Defaults to true.




    * asynchronousReplicationIntervalMillis=<number of milliseconds> - The asynchronous
      replicator runs at a set interval of milliseconds. The default is 1000. The minimum
      is 10. This property is only applicable if replicateAsynchronously=true


    * asynchronousReplicationMaximumBatchSize=<number of operations> - The maximum
      number of operations that will be batch within a single RMI message.  The default
      is 1000. This property is only applicable if replicateAsynchronously=true


    The RMIBootstrapCacheLoader bootstraps caches in clusters where RMICacheReplicators are
    used. It is configured as per the following example:


    <bootstrapCacheLoaderFactory
        class="net.sf.ehcache.distribution.RMIBootstrapCacheLoaderFactory"
        properties="bootstrapAsynchronously=true, maximumChunkSizeBytes=5000000"/>


    The RMIBootstrapCacheLoaderFactory recognises the following optional properties:


    * bootstrapAsynchronously=true|false - whether the bootstrap happens in the background
      after the cache has started. If false, bootstrapping must complete before the cache is
      made available. The default value is true.


    * maximumChunkSizeBytes=<integer> - Caches can potentially be very large, larger than the
      memory limits of the VM. This property allows the bootstraper to fetched elements in
      chunks. The default chunk size is 5000000 (5MB).


    -->




    <!--
    Mandatory Default Cache configuration. These settings will be applied to caches
    created programmtically using CacheManager.add(String cacheName)
    -->
    <defaultCache
            maxElementsInMemory="10000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            maxElementsOnDisk="10000000"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU">
        <persistence strategy="localTempSwap"/>
    </defaultCache>
    <cache name="dictionaryCache"
            maxElementsInMemory="10000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            maxElementsOnDisk="10000000"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU">
        <persistence strategy="localTempSwap"/>
    </cache>
    
</ehcache>
<!--  
<diskStore>==========当内存缓存中对象数量超过maxElementsInMemory时,将缓存对象写到磁盘缓存中(需对象实现序列化接口)  
<diskStore path="">==用来配置磁盘缓存使用的物理路径,Ehcache磁盘缓存使用的文件后缀名是*.data和*.index  
name=================缓存名称,cache的唯一标识(ehcache会把这个cache放到HashMap里)  
maxElementsOnDisk====磁盘缓存中最多可以存放的元素数量,0表示无穷大  
maxElementsInMemory==内存缓存中最多可以存放的元素数量,若放入Cache中的元素超过这个数值,则有以下两种情况  
                     1)若overflowToDisk=true,则会将Cache中多出的元素放入磁盘文件中  
                     2)若overflowToDisk=false,则根据memoryStoreEvictionPolicy策略替换Cache中原有的元素  
eternal==============缓存中对象是否永久有效,即是否永驻内存,true时将忽略timeToIdleSeconds和timeToLiveSeconds  
timeToIdleSeconds====缓存数据在失效前的允许闲置时间(单位:秒),仅当eternal=false时使用,默认值是0表示可闲置时间无穷大,此为可选属性  
                     即访问这个cache中元素的最大间隔时间,若超过这个时间没有访问此Cache中的某个元素,那么此元素将被从Cache中清除  
timeToLiveSeconds====缓存数据在失效前的允许存活时间(单位:秒),仅当eternal=false时使用,默认值是0表示可存活时间无穷大  
                     即Cache中的某元素从创建到清楚的生存时间,也就是说从创建开始计时,当超过这个时间时,此元素将从Cache中清除  
overflowToDisk=======内存不足时,是否启用磁盘缓存(即内存中对象数量达到maxElementsInMemory时,Ehcache会将对象写到磁盘中)  
                     会根据标签中path值查找对应的属性值,写入磁盘的文件会放在path文件夹下,文件的名称是cache的名称,后缀名是data  
diskPersistent=======是否持久化磁盘缓存,当这个属性的值为true时,系统在初始化时会在磁盘中查找文件名为cache名称,后缀名为index的文件  
                     这个文件中存放了已经持久化在磁盘中的cache的index,找到后会把cache加载到内存  
                     要想把cache真正持久化到磁盘,写程序时注意执行net.sf.ehcache.Cache.put(Element element)后要调用flush()方法  
diskExpiryThreadIntervalSeconds==磁盘缓存的清理线程运行间隔,默认是120秒  
diskSpoolBufferSizeMB============设置DiskStore(磁盘缓存)的缓存区大小,默认是30MB  
memoryStoreEvictionPolicy========内存存储与释放策略,即达到maxElementsInMemory限制时,Ehcache会根据指定策略清理内存  
                                 共有三种策略,分别为LRU(最近最少使用)、LFU(最常用的)、FIFO(先进先出)  
-->  


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值