java框架-15spring4_mybatis04-EHcahce-logback

1.代码区

  

package cn.sxt.dao;

import java.util.List;

import cn.sxt.vo.User;

public interface UserDao {
     List<User> selectUser();
    int insert(User user); 
}
 
UserDao
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.sxt.dao.UserDao">
    <select id="selectUser" resultType="cn.sxt.vo.User">
        select * from user
    </select>
    <insert id="insert" parameterType="cn.sxt.vo.User" useGeneratedKeys="true">
        insert into user(name,pwd) values(#{name},#{pwd})
    </insert>
    <delete id="remove">
        deletes from user where id=#{id}
    </delete>
</mapper>
user.mapper.xml
package cn.sxt.service;

import java.util.List;

import org.springframework.stereotype.Service;

import cn.sxt.vo.User;

public interface UserService {
    List<User> selectUser();
    int   insert(User user);
      
}
UserService
package cn.sxt.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import cn.sxt.dao.UserDao;
import cn.sxt.service.UserService;
import cn.sxt.vo.User;

@Service
public class UserServiceImpl implements UserService {


    @Resource
    private UserDao userDao;
    
    //key不是必须的
    @Cacheable(value = "ehcache_test",key="'user'+#key")  
    public List<User> selectUser(){
        return userDao.selectUser();
    }
    
      //清空该value的缓存
    @CacheEvict(value="ehcache_test",key="0",beforeInvocation=true)
    public int insert(User user) {
        return userDao.insert(user);
    }

}
UserServiceImpl
package cn.sxt.test;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import cn.sxt.dao.UserDao;
import cn.sxt.service.UserService;
import cn.sxt.vo.User;

public class Test {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        UserService userDao = (UserService)context.getBean(UserService.class);
        System.out.println(userDao.insert(new User("min", 1, "ad")));
        System.out.println(userDao.selectUser().size());
        //test();
    }
    
    public static void test() {
        //ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        
    /*ApplicationContext context = new ClassPathXmlApplicationContext("springMVV-servlet.xml");
        UserDao userDao = (UserDao)context.getBean(UserDao.class);
        System.out.println(userDao.insert(new User("zhangsna", "1234")));
        System.out.println(userDao.selectUser().size());*/
          // 1. 创建缓存管理器
       // CacheManager cacheManager = CacheManager.create("./src/main/resources/ehcache.xml");
         CacheManager cacheManager = CacheManager.create("src/ehcache.xml");

        // 2. 获取缓存对象
        Cache cache = cacheManager.getCache("ehcache_test");

      /*  // 3. 创建元素
        Element element = new Element("key", "value1");
      //  Element element1 = new Element("key1", "value1");
        Element element3 = new Element("key3", "value1");
        Element element4 = new Element("key4", "value1");
        Element element5 = new Element("key5", "value1");
        Element element6 = new Element("key6", "value1");
        Element element7 = new Element("key7", "value1");
        Element element8 = new Element("key8", "value1");
        Element element9= new Element("key9","value1");
        Element element0 = new Element("key0", "value1");

        // 4. 将元素添加到缓存
        cache.put(element);
        cache.put(element1);
         cache.put(element3);
        cache.put(element4);
        cache.put(element5);
        cache.put(element6);
        cache.put(element7);
        cache.put(element8);
        cache.put(element9);
        cache.put(element0);

        // 5. 获取缓存
        Element value = cache.get("key");
        //[ key = key1, value=value1, version=1, hitCount=1, CreationTime = 1517537797608, LastAccessTime = 1517537797611 ]
        System.out.println("key1+++++++++++"+value);
          //value1
        System.out.println("value.getObjectValue()+++++++++++++++++"+value.getObjectValue());

        // 6. 删除元素
        cache.remove("key");*/

        User dog  = new User("taidi",1000,"taile");
        User dog1 = new User("taidi",1000,"taile");
        User dog2 = new User("taidi",1000,"taile");
        User dog3 = new User("taidi",1000,"taile");
        User dog4 = new User("taidi",1000,"taile");
        User dog5 = new User("taidi",1000,"taile");
        User dog6 = new User("taidi",1000,"taile");
        Element element0 = new Element("taidi", dog);
        Element element1 = new Element("taidi1", dog1);
        Element element2 = new Element("taidi2", dog2);
        Element element3 = new Element("taidi3", dog3);
        Element element4 = new Element("taidi4", dog4);
        Element element5 = new Element("taidi5", dog5);
        Element element6 = new Element("taidi6", dog6);
        Element element7 = new Element("taidi7", dog6);
        Element element8 = new Element("taidi8", dog6);
        cache.put(element0);
        cache.put(element1);
        cache.put(element2);
        cache.put(element3);
        cache.put(element4);
        cache.put(element5);
        cache.put(element6);
        cache.put(element7);
        cache.put(element8);
        Element value2 = cache.get("taidi1");
        User dog12 = (User) value2.getObjectValue();
        //User [id=1000, name=taidi, pwd=taile]
        System.out.println(dog12);
        //1
        System.out.println(cache.getSize());
        for (String cacheName : cacheManager.getCacheNames()) {
            System.out.println(cacheName);
        }
        // 获取所有的缓存对象
        for (Object key : cache.getKeys()) {
            System.out.println(key);
        }
         
  
        // 得到缓存对象占用内存的大小
      System.out.println(cache.getMemoryStoreSize());
     
        // 7. 刷新缓存
        cache.flush();

        // 8. 关闭缓存管理器
       cacheManager.shutdown();        
    }
}
Test
package cn.sxt.vo;

import java.io.Serializable;


public class User implements Serializable{
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    /**
     * 
     */
    private int id;
    private String name;
    private String pwd;
    
    
    public User() {
        super();
    }

    public User(String name,int id,  String pwd) {
        super();
        this.id = id;
        this.name = name;
        this.pwd = pwd;
    }

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPwd() {
        return pwd;
    }
    public void setPwd(String pwd) {
        this.pwd = pwd;
    }
}
User
<?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:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:cache="http://www.springframework.org/schema/cache"
    xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
        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.1.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd">
    <context:property-placeholder location="classpath:jdbc.properties"/>
    <!-- 配置数据源 -->
    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${jdbc.driverClassName}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
    </bean>
    <!-- 声明式事务配置 开始 -->
    <!-- 配置事务管理器 -->
    <bean id="txManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>
    <!-- 配置事务通知 -->
    <tx:advice id="txAdvice" transaction-manager="txManager">
        <tx:attributes>
            <!-- 配置哪些方法使用什么样的事务,配置事务的传播特性 -->
            <tx:method name="add" propagation="REQUIRED" />
            <tx:method name="insert" propagation="REQUIRED" />
            <tx:method name="update" propagation="REQUIRED" />
            <tx:method name="delete" propagation="REQUIRED" />
            <tx:method name="remove*" propagation="REQUIRED" />
            <tx:method name="get" read-only="true" />
            <tx:method name="*" propagation="REQUIRED" />
        </tx:attributes>
    </tx:advice>
    <aop:config>
        <aop:pointcut expression="execution(* cn.sxt.service.impl.*.*(..))"
            id="pointcut" />
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut" />
    </aop:config>
    <!-- 声明式事务配置 结束 -->
    <!-- 配置sqlSessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="mapperLocations" value="classpath:cn/sxt/dao/*.mapper.xml"></property>
    </bean>
    <context:component-scan base-package="cn.sxt" />
    <!-- 6.spring和mybaits整合,自动扫映射输入参数 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="cn.sxt.dao" />
    </bean>
    
    
    
    
    <!-- ehcache 缓存配置 -->
    <cache:annotation-driven cache-manager="cacheManager" />  
    <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">  
        <property name="cacheManager" ref="ehcache"></property>  
    </bean>  
    <bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">  
        <property name="configLocation" value="classpath:ehcache.xml"></property>  
    </bean> 
</beans>
bean.xml
<ehcache>  
<!-- <diskStore>==========当内存缓存中对象数量超过maxElementsInMemory时,将缓存对象写到磁盘缓存中(需对象实现序列化接口)  
<diskStore path="">==用来配置磁盘缓存使用的物理路径,Ehcache磁盘缓存使用的文件后缀名是*.data和*.index   -->
    <diskStore path="D://xp"/>  

    <defaultCache  
           maxElementsInMemory="1000"  
           eternal="false"  
           timeToIdleSeconds="120"  
           timeToLiveSeconds="120"  
           overflowToDisk="false"/>  


     <cache 
         name="ehcache_test" 
         eternal="true" 
         maxElementsInMemory="10"
         overflowToDisk="true" 
         diskPersistent="false" 
         timeToIdleSeconds="2"
         timeToLiveSeconds="3" 
         memoryStoreEvictionPolicy="LRU" />
</ehcache>  
<!--  
name============cache的唯一标识(ehcache会把这个cache放到HashMap里)  
eternal===========缓存中对象是否永久有效,即是否永驻内存,true时将忽略timeToIdleSeconds和timeToLiveSeconds  
maxElementsOnDisk====磁盘缓存中最多可以存放的元素数量,0表示无穷大  
maxElementsInMemory==内存缓存中最多可以存放的元素数量,若放入Cache中的元素超过这个数值,则有以下两种情况  
    1)若overflowToDisk=true,则会将Cache中多出的元素放入磁盘文件中  
    2)若overflowToDisk=false,则根据memoryStoreEvictionPolicy策略替换Cache中原有的元素  
diskPersistent========默认为false,是否持久化磁盘缓存,当这个属性的值为true时,系统在初始化时会在磁盘中查找文件名为cache名称,后缀名为index的文件  
                     这个文件中存放了已经持久化在磁盘中的cache的index,找到后会把cache加载到内存  
                     要想把cache真正持久化到磁盘,写程序时注意执行net.sf.ehcache.Cache.put(Element element)后要调用flush()方法  
timeToIdleSeconds====缓存数据在失效前的允许闲置时间(单位:秒),仅当eternal=false时使用,默认值是0表示可闲置时间无穷大,此为可选属性  
                     即访问这个cache中元素的最大间隔时间,若超过这个时间没有访问此Cache中的某个元素,那么此元素将被从Cache中清除  
timeToLiveSeconds====缓存数据在失效前的允许存活时间(单位:秒),仅当eternal=false时使用,默认值是0表示可存活时间无穷大  
                     即Cache中的某元素从创建到清楚的生存时间,也就是说从创建开始计时,当超过这个时间时,此元素将从Cache中清除  
diskExpiryThreadIntervalSeconds==磁盘缓存的清理线程运行间隔,默认是120秒  
diskSpoolBufferSizeMB============设置DiskStore(磁盘缓存)的缓存区大小,默认是30MB  
memoryStoreEvictionPolicy========内存存储与释放策略,即达到maxElementsInMemory限制时,Ehcache会根据指定策略清理内存  
                                 共有三种策略,分别为LRU(最近最少使用)、LFU(最常用的)、FIFO(先进先出)  
-->
ehcache.xml
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/orcl
jdbc.username=root
jdbc.password=123456
jdbc.properties
原文地址:https://www.cnblogs.com/ou-pc/p/8543774.html