Home IT Linux Windows Database Network Programming Server Mobile  
           
  Home \ Programming \ Spring Integration ehcache annotation implement the query cache and cache update or delete instant     - DB2 manually create a library (Database)

- Applications Linux leap second problem caused (Linux)

- Ubuntu installed racing game Speed Dreams 2.1 (Linux)

- Linux uses a screen recording under RecordMyDesktop (Linux)

- Verify the character set on MyCAT (Database)

- Shell Script: create a function and specify a directory for download (Programming)

- JavaScript prototype and prototype chain and project combat (Programming)

- IDS Intrusion Detection System built (Linux) (Linux)

- Nginx reverse proxy and self-signed https (Server)

- JSON data normalization (normalize) (Programming)

- wget command examples (Linux)

- java.net.NoRouteToHostException of Hadoop problem: no route to host (Server)

- Linux Security Module (LSM) Introduction (Linux)

- How to install the client sqlplus under linux (Database)

- Oracle database physical file backup / restore (Database)

- Boot automatically remove Linux operating history records (Linux)

- JavaScript function definition mode (Programming)

- SLF4J Tutorial (Programming)

- To_teach you three strategies to prevent the LAN IP address theft (Linux)

- Use LVM partition on Ubuntu and easily adjust the snapshot (Linux)

 
         
  Spring Integration ehcache annotation implement the query cache and cache update or delete instant
     
  Add Date : 2018-11-21      
         
       
         
  EDITORIAL: Previous blog wrote a basic introduction to spring cache and ehcache of personal recommendations put these basic knowledge about the topic to be feeling today. Not much to say, open dry!

NOTE: introducing jar

        < ! - Introducing ehcache Cache ->
        < Dependency>
            < GroupId> net.sf.ehcache
            < ArtifactId> ehcache < / artifactId>
            < Version> 2.8.3 < / version>
        < / Dependency>

The first step: first configure ehcache.xml

< ? Xml version = "1.0" encoding = "UTF-8"?>
< Ehcache xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance"
        xsi: noNamespaceSchemaLocation = "ehcache.xsd"
        updateCheck = "true" monitoring = "autodetect"
        dynamicConfig = "true">
    
  < DiskStore path = "java.io.tmpdir" />
  < DefaultCache
            maxEntriesLocalHeap = "10000"
            eternal = "false"
            overflowToDisk = "false"
            timeToIdleSeconds = "120"
            timeToLiveSeconds = "120"
            diskSpoolBufferSizeMB = "30"
            maxEntriesLocalDisk = "10000000"
            diskExpiryThreadIntervalSeconds = "120"
            memoryStoreEvictionPolicy = "LRU">
        < Persistence strategy = "localTempSwap" />
    < / DefaultCache>
  
    < Cache name = "myCache"
          maxEntriesLocalHeap = "10000"
          maxEntriesLocalDisk = "1000"
          eternal = "false"
          diskSpoolBufferSizeMB = "30"
          timeToIdleSeconds = "300"
          timeToLiveSeconds = "600"
          memoryStoreEvictionPolicy = "LFU"
          transactionalMode = "off">
        < Persistence strategy = "localTempSwap" />
    < / Cache>
< / Ehcache>

Step Two: Introduce schema in spring.xml configuration file,

xmlns: aop = "http://www.springframework.org/schema/aop" and http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache -3.2.xsd

Cached profile:

< ! - Enable caching annotation feature, this is a must, otherwise the annotations will not take effect. In addition, the notes must be declared in the spring main configuration file to take effect ->
    < Cache: annotation-driven cache-manager = "ehcacheManager" />
    
    < -! CacheManager factory class specified ehcache.xml here ->
    < Bean id = "ehcacheManagerFactory" class = "org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
        < Property name = "configLocation" value = "classpath: ehcache.xml" />
    < / Bean>
    < ! - Declare cacheManager ->
    < Bean id = "ehcacheManager" class = "org.springframework.cache.ehcache.EhCacheCacheManager">
        < Property name = "cacheManager" ref = "ehcacheManagerFactory" />
    < / Bean>

OK! Caching configuration has been completed. Let's start to write the test program. It should connect to the database, I do not write. For convenience it before stuffing written model, this model is a log management entity AOP annotations to achieve in order to be lazy on the direct use, I hope you do not misunderstand, there is no special meaning

The third step: the preparation model, It should be noted that to achieve the cached entity must be serialized private static final long serialVersionUID = -6579533328390250520L; on the sequence of the generation is not presented here, we can look at Baidu.

package org.shop.entity;

import java.io.Serializable;
import java.util.Date;

public class SystemLog implements Serializable {
 
    private static final long serialVersionUID = -6579533328390250520L;

    private String id;

    private String description;

    private String method;

    private Long logType;

    private String requestIp;

    private String exceptioncode;

    private String exceptionDetail;

    private String params;

    private String createBy;

    private Date createDate;

    public String getId () {
        return id;
    }

    public void setId (String id) {
        this.id = id == null ? null : id.trim();
    }

    public String getDescription () {
        return description;
    }

    public void setDescription (String description) {
        this.description = description == null ? null : description.trim();
    }

    public String getMethod () {
        return method;
    }

    public void setMethod (String method) {
         this.method = method == null ? null : method.trim();
    }

    public Long getLogType () {
        return logType;
    }

    public void setLogType (Long logType) {
        this.logType = logType;
    }

    public String getRequestIp () {
        return requestIp;
    }

    public void setRequestIp (String requestIp) {
        this.requestIp = requestIp == null ? null : requestIp.trim();
    }

    public String getExceptioncode () {
        return exceptioncode;
    }

    public void setExceptioncode (String exceptioncode) {
        this.exceptioncode = exceptioncode == null ? null : exceptioncode.trim();
    }

    public String getExceptionDetail () {
        return exceptionDetail;
    }

    public void setExceptionDetail (String exceptionDetail) {
         this.exceptionDetail = exceptionDetail == null ? null : exceptionDetail.trim();
    }

    public String getParams () {
        return params;
    }

    public void setParams (String params) {
        this.params = params == null ? null : params.trim();
    }

    public String getCreateBy () {
        return createBy;
    }

    public void setCreateBy (String createBy) {
        this.createBy = createBy == null ? null : createBy.trim();
    }

    public Date getCreateDate () {
        return createDate;
    }

    public void setCreateDate (Date createDate) {
        this.createDate = createDate;
    }
}

Step Four: Write dao, service

package org.shop.dao;

import org.shop.entity.SystemLog;

public interface SystemLogMapper {
    int deleteByPrimaryKey (String id);

    int insert (SystemLog record);

    int insertSelective (SystemLog record);

    SystemLog selectByPrimaryKey (String id);

    int updateByPrimaryKeySelective (SystemLog record);

    int updateByPrimaryKey (SystemLog record);
    
    int count ();
}


public interface SystemLogService {

    int deleteSystemLog (String id);

    int insert (SystemLog record);
    
    int insertTest (SystemLog record);

    SystemLog findSystemLog (String id);
    
    int updateSystemLog (SystemLog record);
    
    int count ();
}

Step Five: Write cache serviceImpl and add annotations. Here annotation cache parameters are not introduced, does not know how to read my previous blog, I comment here, first of all you need to write, and one will introduce one by one.

@Service ( "SystemLogService")
public class SystemLogServiceImpl implements SystemLogService {

    @Resource
    private SystemLogMapper systemLogMapper;
    
    @Override
    public int deleteSystemLog (String id) {
              return systemLogMapper.deleteByPrimaryKey (id);
    }

    @Override
    // @ CachePut (value = "myCache")
    // @ CacheEvict (value = "myCache", allEntries = true, beforeInvocation = true)
    @CacheEvict (Value = "myCache", key = "0", beforeInvocation = true)
    public int insert (SystemLog record) {
              return systemLogMapper.insertSelective (record);
    }

    @Override
    @Cacheable (Value = "myCache", key = "# id")
    public SystemLog findSystemLog (String id) {
            return systemLogMapper.selectByPrimaryKey (id);
    }

    @Override
    public int updateSystemLog (SystemLog record) {
            return systemLogMapper.updateByPrimaryKeySelective (record);
    }
    @Override
    public int insertTest (SystemLog record) {
          return systemLogMapper.insert (record);
    }

    @Override
    @Cacheable (Value = "myCache", key = "0")
    public int count () {
          int num = systemLogMapper.count ();
          return num;
    }

}

Step Six: Write controller, that is our test.

@Controller
@RequestMapping ( "SystemLogController")
public class SystemLogController {

    @Resource
    private SystemLogService systemLogService;
    
    @RequestMapping ( "TestLog")
    public ModelAndView testLog () {
        ModelMap modelMap = new ModelMap ();
        SystemLog systemLog = systemLogService.findSystemLog ( "c30e2398-079a-406b-a2f7-a85fa15ccac7");
        modelMap.addAttribute ( "data", systemLog);
        return new ModelAndView ( "index", modelMap);
    }
    @RequestMapping ( "Insert")
    @ResponseBody
    public boolean Insert (SystemLog record) {
        systemLogService.insert (record);
        return true;
    }
    
    @RequestMapping ( "Test1")
    public ModelAndView test1 () {
        ModelMap modelMap = new ModelMap ();
        int num = systemLogService.count ();
        modelMap.addAttribute ( "num", num);
        return new ModelAndView ( "pageEhcache", modelMap);
    }
    
}

We first tested the query cache that serviceImpl in findSystemLog (String id) method, we visited testLog.do.

Here we look serviceImpl the insert method and count () method, count method is to record the data tables in total, insert the table is to add a recording, insert cache annotations using @CacheEvict (value = "myCache", key = "0", beforeInvocation = true), here is the designated clearing the cache, which is the count method @Cacheable (value = "myCache", key = "0") is, (serviceImpl in the comments! CacheEvict (value = "myCache", allEntries = true, beforeInvocation = true) is to clear all cache, I will not demonstrate, is the same reason)

Here I provide a test pageEhcache.jsp page,

< % @ Page language = "java" import = "java.util. *" PageEncoding = "UTF-8"%>
< %
String path = request.getContextPath ();
String basePath = request.getScheme () + ": //" + request.getServerName () + ":" + request.getServerPort () + path + "/";
%>
< ! DOCTYPE HTML PUBLIC "- // W3C // DTD HTML 4.01 Transitional // EN">
< Html>
  < Head>
    < Title> Test < / title>
    < Script type = "text / javascript" src = "< % = request.getContextPath ()%> / js / jquery-1.11.1.min.js"> < / script>
    < Script type = "text / javascript">
      function insert () {
          var record = $ ( "# formID") serializeArray ().;
          console.info (record);
          $ .ajax ({
                  url: "< % = request.getContextPath ()%> / systemLogController / insert.do",
                  type: 'post',
                  async: true,
                  dataType: 'json',
                  data: record,
                  success: function (result) {
                      alert ( "inserted successfully!");
                  }
          });
      }
    < / Script>
  < / Head>
  < Body>
  < H1> < % = new Date ()%> < / h1>
  < H1> This is a practice < / h1>
    < Form id = "formID" action = "">
        id: < input name = "id" type = "text" /> < br>
        < Input type = "button" value = "insert" onclick = "insert ()" />
    < / Form>
    < br>
    total:
    < H4> $ {num} < / h4>
  < / Body>
< / Html>

On the insert () method also @CachePut (value = "myCache") notes, annotations serviceImpl above, and its role is: @CachePut annotated method before executing the cache will not go before checking whether there is executed It results, but each time the method is performed, and the results of key-value pairs stored in the specified cache.

I'm not here to do presentations, and you can try it yourself.

Summary: I understand, easy to query methods to increase the cache, but the cache update process is more trouble, I wrote above serviceImpl three treatments,

1. @CachePut process, this method needs to be consistent to specify the cache key, in spite of this, or not, because it returns the object cache is the record number int (added or deleted or modified, or that record, which we Discover all or part of the record buffer or feasible)

2. @CacheEvict (value = "myCache", key = "0", beforeInvocation = true) process, we specify clear the cache key, in this way the disadvantage is trouble, we need to pay attention to every cache key

3. @CacheEvict (value = "myCache", allEntries = true, beforeInvocation = true) process, clear all caches, in this way the most convenient, but also with other caches will be cleared.

With the increasing complexity of the business, these treatments may increase the complexity of the code, and then I think of is the DB layer cache, you can use redis, mamchched for processing. Of course, for the average web application using ehcache has carved a settled, but the effect of using db-level caching performance for large amounts of data could be better.
     
         
       
         
  More:      
 
- grep command Series: How to Use the grep command in Linux / UNIX (Linux)
- Configuring Allatori code confusion when developing general Java applications in NetBeans (Programming)
- Spring declarative transaction management (Programming)
- 10 Linux in the passwd command examples (Linux)
- VMware virtual machine to use bridged mode fast Internet access (Linux)
- CentOS source installation GitLab Chinese Version (Server)
- You know the difference between URL, URI and URN among you (Linux)
- VMware ghost Linux card error (Linux)
- Based on a complete solution RMI service to transfer large files (Programming)
- SteamOS installation under Ubuntu 14.04 (Linux)
- Upgrading Oracle 11.2.0.1 to 11.2.0.3 (Database)
- Doubly linked list basic operations (Linux)
- Struts2 study notes -Valuestack (value stack) and OGNL expression (Programming)
- Ubuntu users to install household financial management tools HomeBank 5.0.0 (Linux)
- Linux System Getting Started Learning: The Linux command line burn ISO or NRG image to DVD (Linux)
- C language binary tree (Programming)
- CentOS 7 RHEL 7 to reset the root password (Linux)
- Linux common commands ll namely ls -l --color = auto (Linux)
- CentOS 6.5 install VNC-Server (Linux)
- MySQL concat function is SQL injection (Linux)
     
           
     
  CopyRight 2002-2016 newfreesoft.com, All Rights Reserved.