spring + ehcache(缓存)

spring 整合 ehcache 进行接口缓存

pom文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.cache</groupId>
    <name>Ehcache</name>
    <artifactId>Ehcache</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <s-version>5.0.4.RELEASE</s-version>
        <comm-version>1.2</comm-version>
        <model-version>1.0-SNAPSHOT</model-version>
        <mysql-v>6.0.6</mysql-v>
        <mybatis-sv>1.3.1</mybatis-sv>
        <mybatis-v>3.4.6</mybatis-v>
        <druid-v>1.1.9</druid-v>
        <fastjson-v>1.2.46</fastjson-v>
        <jackson-v>2.9.4</jackson-v>
        <ehcache-v>3.5.2</ehcache-v>
        <netEhcache-v>2.10.4</netEhcache-v>
    </properties>
    <!--<dependencyManagement>-->
        <dependencies>
            <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context</artifactId>
                <version>${s-version}</version>
            </dependency>
            <!-- https://mvnrepository.com/artifact/org.springframework/spring-context-support -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context-support</artifactId>
                <version>${s-version}</version>
            </dependency>
            <!-- https://mvnrepository.com/artifact/org.springframework/spring-web -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-webmvc</artifactId>
                <version>${s-version}</version>
            </dependency>
            <!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
            <dependency>
                <groupId>commons-logging</groupId>
                <artifactId>commons-logging</artifactId>
                <version>${comm-version}</version>
            </dependency>
            <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-jdbc</artifactId>
                <version>${s-version}</version>
            </dependency>

            <!--model&&&&&&&&&&&&&&&&&&&&-->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>${mysql-v}</version>
            </dependency>
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis-spring</artifactId>
                <version>${mybatis-sv}</version>
            </dependency>
            <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>${mybatis-v}</version>
            </dependency>
            <!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid</artifactId>
                <version>${druid-v}</version>
            </dependency>

            <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>fastjson</artifactId>
                <version>${fastjson-v}</version>
            </dependency>
            <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-databind</artifactId>
                <version>${jackson-v}</version>
            </dependency>
            <!--缓存-->
            <dependency>
                <groupId>org.ehcache</groupId>
                <artifactId>ehcache</artifactId>
                <version>${ehcache-v}</version>
            </dependency> 
            <!-- https://mvnrepository.com/artifact/com.googlecode.ehcache-spring-annotations/ehcache-spring-annotations -->
            <dependency>
                <groupId>com.googlecode.ehcache-spring-annotations</groupId>
                <artifactId>ehcache-spring-annotations</artifactId>
                <version>1.2.0</version>
            </dependency>

        </dependencies>
    <!--</dependencyManagement>-->
        <build>
            <plugins>
            <plugin>
                <!-- https://mvnrepository.com/artifact/org.apache.tomcat/tomcat 内嵌式tomcat-->
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.2</version>
                <configuration>
                    <port>9090</port>
                    <path>/</path>
                    <uriEncoding>UTF-8</uriEncoding>
                    <server>tomcat7</server>
                </configuration>
            </plugin>
        </plugins>
        </build>
</project>

注意jar包冲突,一般真的好难发现

项目结构

这里写图片描述

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->

<!--
  - This is the Cocoon web-app configurations file
  -
  - $Id$
  -->
<web-app version="2.4"
         xmlns="http://java.sun.com/xml/ns/j2ee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
  <servlet>
    <servlet-name>ehcache</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
     <!--初始化上下文-->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath*:ehcache-servlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>


  <servlet-mapping>
    <servlet-name>ehcache</servlet-name>
    <url-pattern>/*</url-pattern>
  </servlet-mapping>

</web-app>    

ehcache.xml

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
         updateCheck="false">

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

   <defaultCache eternal="false"
                 overflowToDisk="false"
                 diskPersistent="false"
                 timeToIdleSeconds="3600"
                 timeToLiveSeconds="3600"
                 memoryStoreEvictionPolicy="LRU"/>

   <cache name="test"
          eternal="false"
          overflowToDisk="false"
          diskPersistent="false"
          timeToIdleSeconds="3600"
          timeToLiveSeconds="3600"
          statistics="false"
   />



   <!--
       eternal="false"   // 元素是否永恒,如果是就永不过期(必须设置)
       maxEntriesLocalHeap="1000" // 内存中最大缓存对象数(必须设置) 设置缓存在本地内存中最大缓存项数量(0表示无限)等效于旧版本中的maxElementsInMemory属性
       overflowToDisk="false"  // 当缓存达到maxElementsInMemory值是,是否允许溢出到磁盘(必须设置)
       diskPersistent="false"  // 磁盘缓存在VM重新启动时是否保持(默认为false)
       timeToIdleSeconds="0" // 当缓存闲置n秒后销毁(秒为单位). 0表示可以永远空闲,默认为0
       timeToLiveSeconds="600" // 元素在缓存里存在的时间(秒为单位). 0 表示永远存在不过期
       memoryStoreEvictionPolicy="LFU" // 当达到maxElementsInMemory时,如何强制进行驱逐默认使用"最近使用(LRU)"策略,其它还有先入先出FIFO,最少使用LFU,较少使用LRU
       statistics="false" 是否开启统计
   -->
</ehcache>

spring-cache.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
       xmlns:cache="http://www.springframework.org/schema/cache" xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                        http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
                        http://www.springframework.org/schema/cache
                        http://www.springframework.org/schema/cache/spring-cache.xsd
                        http://www.springframework.org/schema/tx
                        http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">

    <description>Spring-cache配置文件</description>
 <!--开启缓存注解-->
    <cache:annotation-driven cache-manager="cacheManager" />

    <bean id="ehcacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
        <property name="configLocation" value="classpath:ehcache.xml"/>
        <property name="shared" value="true"/>
    </bean>

    <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
        <property name="cacheManager" ref="ehcacheManager"/>
        <property name="transactionAware" value="true"/>
    </bean>
</beans>

cache-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:cache="http://www.springframework.org/schema/cache"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
          http://www.springframework.org/schema/beans/spring-beans.xsd
          http://www.springframework.org/schema/cache
          http://www.springframework.org/schema/cache/spring-cache-4.0.xsd
          http://www.springframework.org/schema/context
          http://www.springframework.org/schema/context/spring-context.xsd">
    <context:annotation-config/>
    <import resource="mvc-data-source-mybatis.xml"/>
    <!--扫描包-->
    <!--com.mv 组名更好的去扫描本地工程的包-->
    <context:component-scan base-package="com.cache"/>
    <!--解析json 参考我的其他文章-->
    <import resource="json-config.xml"/>
     <!--导入缓存配置文件-->
    <import resource="spring-cache.xml"/>
</beans>

参考代码

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.cache.controller;

import com.alibaba.fastjson.JSONObject;
import com.cache.model.Test;
import com.cache.server.TestService;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 *
 * @author xuzz
 */
@RestController
@RequestMapping("/test/")
public class TestController {
    @Autowired
    private TestService testService;
    @RequestMapping("test")
    public JSONObject findList(){
        JSONObject jSONObject = new JSONObject();
        List<Test> tests = testService.findList();
        jSONObject.put("data", tests);
        return jSONObject;
    }
    /**
     *   清除缓存
     */
    @RequestMapping("rem")
    //无论成功失败都进行清除
    @CacheEvict(value = "test",beforeInvocation = true)
    public void removeCache(){
        System.out.println("清除缓存");
    }
}

题外数据源+mybatis配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
          http://www.springframework.org/schema/beans/spring-beans.xsd
          http://www.springframework.org/schema/context
          http://www.springframework.org/schema/context/spring-context.xsd">
    <!--数据源配置-->
    <!--<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="url" value="jdbc:mysql://192.168.0.120:3306/testok?useSSL=false&amp;serverTimezone=UTC&amp;characterEncoding=utf-8"/>
        <property name="username" value="root"/>
        <property name="password" value="tiger"/>
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
    </bean>
    <!--mybatis 配置-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="mapperLocations" value="classpath*:com/cache/mapper/**/*Mapper.xml"/>
    </bean>
    <!--扫描dao包-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.cache.mapper"/>
        <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
    </bean>
</beans>

猜你喜欢

转载自blog.csdn.net/xuzz94/article/details/79703465