SSM框架之整合EhCache

本文主要讲ssm框架整合EhCache。或许有人会问什么是ehcache。

关于EhCache的介绍和优劣,我想下面的解答足以让读者明白:

EhCache 是一个纯Java的进程内缓存框架,具有快速、精干等特点,是Hibernate中默认的CacheProvider。Ehcache是一种广泛使用的开 源Java分布式缓存。主要面向通用缓存,Java EE和轻量级容器。它具有内存和磁盘存储,缓存加载器,缓存扩展,缓存异常处理程序,一个gzip缓存servlet过滤器,支持REST和SOAP api等特点。

优点: 
1. 快速 
2. 简单 
3. 多种缓存策略 
4. 缓存数据有两级:内存和磁盘,因此无需担心容量问题 
5. 缓存数据会在虚拟机重启的过程中写入磁盘 
6. 可以通过RMI、可插入API等方式进行分布式缓存 
7. 具有缓存和缓存管理器的侦听接口 
8. 支持多缓存管理器实例,以及一个实例的多个缓存区域 
9. 提供Hibernate的缓存实现

缺点: 
1. 使用磁盘Cache的时候非常占用磁盘空间:这是因为DiskCache的算法简单,该算法简单也导致Cache的效率非常高。它只是对元素直接追加存储。因此搜索元素的时候非常的快。如果使用DiskCache的,在很频繁的应用中,很快磁盘会满。 
2. 不能保证数据的安全:当突然kill掉java的时候,可能会产生冲突,EhCache的解决方法是如果文件冲突了,则重建cache。这对于Cache 数据需要保存的时候可能不利。当然,Cache只是简单的加速,而不能保证数据的安全。如果想保证数据的存储安全,可以使用Bekeley DB Java Edition版本。这是个嵌入式数据库。可以确保存储安全和空间的利用率。

 

或许还有人很疑惑缓存,什么是缓存?为什么需要缓存?

引用百度百科的回答:

缓存就是数据交换的缓冲区(称作Cache),当某一硬件要读取数据时,会首先从缓存中查找需要的数据,如果找到了则直接执行,找不到的话则从内存中找。由于缓存的运行速度比内存快得多,故缓存的作用就是帮助硬件更快地运行。

因为缓存往往使用的是RAM(断电即掉的非永久储存),所以在用完后还是会把文件送到硬盘存储器里永久存储。电脑里最大的缓存就是内存条了,最快的是CPU上镶的L1和L2缓存,显卡的显存是给显卡运算芯片用的缓存,硬盘上也有16M或者32M的缓存。

或许还有人会问内存是什么?

引用百度百科的回答:

内存是计算机中重要的部件之一,它是与CPU进行沟通的桥梁。计算机中所有程序的运行都是在内存中进行的,因此内存的性能对计算机的影响非常大。内存(Memory)也被称为内存储器,其作用是用于暂时存放CPU中的运算数据,以及与硬盘外部存储器交换的数据。只要计算机在运行中,CPU就会把需要运算的数据调到内存中进行运算,当运算完成后CPU再将结果传送出来,内存的运行也决定了计算机的稳定运行。 内存是由内存芯片、电路板、金手指等部分组成的。

也许还人会骂我,说你怎么尽引用百度百科。

我的回答是,因为我对此也不知道怎么回答。

如果让我回答在开发中为什么需要缓存及其缓存的作用,我的回答是,对于有些数据,我只需查询一遍就可以,不需要再度查询,因为有缓存。就好比数据库优化,除了索引之外,还有就是将数据库里面的数据缓存起来,这样对于大规模数据,平常需要多次查询,导致耗费时间很长,性能差,但是我通过缓存,只需查询一次,当再次查询时,就非常快,对整个系统的响应和性能也不会有什么影响。当然了,当涉及到缓存的数据与实际数据库中的数据存在差异时,这里后续会讲采取怎样的方式解决这个问题。

另外建议软件开发的朋友们,有空多多去熟悉熟悉计算机相关的理论知识。正所谓有句话叫做:万变不离其宗。这个其宗在计算机中可以理解为算法与数据结构、操作系统、TCP/IP、计算机基础知识、编译原理等等。把握好这些,编程之路才能越走越长。

这也是一位朋友对我说的。

下面进入正题,关于SSM框架整合EhCache

 

sql脚本准备

CREATE TABLE `user` (
  `user_id` int(8) NOT NULL AUTO_INCREMENT COMMENT '用户主键',
  `login_code` varchar(20) NOT NULL COMMENT '用户编码(登录账户) 手机号 邮箱号',
  `user_name` varchar(20) NOT NULL COMMENT '用户名',
  `password` varchar(40) NOT NULL COMMENT '密码',
  `sex` int(2) NOT NULL COMMENT '性别',
  `identity_card` varchar(20) DEFAULT NULL COMMENT '身份证',
  `create_time` datetime NOT NULL COMMENT '创建时间',
  `create_by` varchar(10) NOT NULL COMMENT '创建人',
  `update_time` datetime NOT NULL COMMENT '更新时间',
  `update_by` varchar(10) NOT NULL COMMENT '更新人',
  `status` int(2) NOT NULL DEFAULT '0' COMMENT '状态:0注册新用户 1邮件认证用户 2管理员 3黑名单',
  PRIMARY KEY (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

 

一、导入Maven依赖

<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.blog</groupId>
  <artifactId>Blog</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <properties>
		<!-- 文件拷贝时的编码 -->  
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>  
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>  
        <!-- 编译时的编码 -->  
        <maven.compiler.encoding>UTF-8</maven.compiler.encoding> 
		<spring.version>4.3.13.RELEASE</spring.version>
		<junit.version>4.12</junit.version>
		<druid.version>1.1.0</druid.version>
		<fastjson.version>1.2.8</fastjson.version>
		<mybaitsplus.version>2.1.8</mybaitsplus.version>
		<mysql.version>5.1.38</mysql.version>
		<log4j.version>1.2.17</log4j.version>
		<slf4j.version>1.7.19</slf4j.version>
		<aspectjweaver.version>1.8.8</aspectjweaver.version>
		<fileupload.version>1.3.1</fileupload.version>
		<jstl.version>1.2</jstl.version>
		<commons-io.version>2.5</commons-io.version>
		<commons-fileupload.version>1.3.1</commons-fileupload.version>
		<ruedigermoeller-fst.version>2.56</ruedigermoeller-fst.version>
		<json.version>20170516</json.version>
		<dozer.version>5.5.1</dozer.version>
		<poi.version>3.14</poi.version>
	</properties>

	<dependencies>
	



       <dependency>
           <groupId>com.alibaba</groupId>
           <artifactId>fastjson</artifactId>
           <version>1.1.46</version>
       </dependency>


       <dependency>
           <groupId>com.google.code.gson</groupId>
           <artifactId>gson</artifactId>
           <version>2.8.0</version>
       </dependency>
       <!-- kisso end -->

		<!-- JUnit -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>${junit.version}</version>
			<scope>test</scope>
		</dependency>
		 <dependency>
		 <!-- jsp -->
	    <groupId>javax.servlet.jsp</groupId>
	     <artifactId>jsp-api</artifactId>
	     <version>2.1</version>
	     <scope>compile</scope>
	    </dependency>
	    <!-- servlet -->
	    <dependency>
	      <groupId>javax.servlet</groupId>
	      <artifactId>javax.servlet-api</artifactId>
	      <version>3.1.0</version>
	      <scope>compile</scope>
	    </dependency>
    

		<!-- Spring -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
			<type>jar</type>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring.version}</version>
			<type>jar</type>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context-support</artifactId>
			<version>${spring.version}</version>
			<type>jar</type>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
			<version>${spring.version}</version>
			<type>jar</type>
			<scope>compile</scope>
		</dependency>
		<dependency>
	      <groupId>org.springframework</groupId>
	      <artifactId>spring-test</artifactId>
		  <version>${spring.version}</version>
	      <scope>compile</scope>
   		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aop</artifactId>
			<version>${spring.version}</version>
			<type>jar</type>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</artifactId>
			<version>${spring.version}</version>
			<type>jar</type>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>${spring.version}</version>
			<type>jar</type>
			<scope>compile</scope>
		</dependency>

		<!-- Spring MVC -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${spring.version}</version>
			<type>jar</type>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring.version}</version>
			<type>jar</type>
			<scope>compile</scope>
		</dependency>

		<!-- AOP -->
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjweaver</artifactId>
			<version>${aspectjweaver.version}</version>
		</dependency>

		<!-- FileUpload -->
		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>${fileupload.version}</version>
		</dependency>

		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>${jstl.version}</version>
		</dependency>

		<!-- Mybatis-Plus -->
		<dependency>
			<groupId>com.baomidou</groupId>
			<artifactId>mybatis-plus</artifactId>
			<version>${mybaitsplus.version}</version>
		</dependency>

		<!-- Mysql -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>${mysql.version}</version>
		</dependency>

		<!-- Druid -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid</artifactId>
			<version>${druid.version}</version>
		</dependency>

		<!-- FastJson -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>${fastjson.version}</version>
		</dependency>

		<!-- Log -->
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>${log4j.version}</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${slf4j.version}</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>${slf4j.version}</version>
		</dependency>
		
		
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-lang3</artifactId>
			<version>3.3.2</version>
		</dependency>
		
		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>${commons-io.version}</version>
		</dependency>
		
		<dependency>
			<groupId>de.ruedigermoeller</groupId>
			<artifactId>fst</artifactId>
			<version>${ruedigermoeller-fst.version}</version>
		</dependency>
	   <dependency>
			<groupId>commons-codec</groupId>
			<artifactId>commons-codec</artifactId>
			<version>1.10</version>
		</dependency>
		
		<dependency>
			<groupId>commons-beanutils</groupId>
			<artifactId>commons-beanutils</artifactId>
			<version>1.9.3</version>
		</dependency>
		
				
		<!-- Json in java  -->
		<dependency>
			<groupId>org.json</groupId>
			<artifactId>json</artifactId>
			<version>20170516</version>
		</dependency>

		<!-- Email -->
		
		<dependency>
			<groupId>com.sun.mail</groupId>
			<artifactId>javax.mail</artifactId>
			<version>1.5.2</version>
			<scope>provided</scope>
		</dependency>
<!-- 		<dependency>
			<groupId>javax.activation</groupId>
			<artifactId>activation</artifactId>
			<version>1.1.1</version>
		</dependency> -->
		
		<!-- 条形码、二维码生成  -->
		<dependency>
			<groupId>com.google.zxing</groupId>
			<artifactId>core</artifactId>
			<version>3.3.0</version>
		</dependency>
		<dependency>
			<groupId>com.google.zxing</groupId>
			<artifactId>javase</artifactId>
			<version>3.3.0</version>
		</dependency>
		
		<!-- User Agent -->
		<dependency>
			<groupId>eu.bitwalker</groupId>
			<artifactId>UserAgentUtils</artifactId>
			<version>1.20</version>
		</dependency>
		
		<!-- Apache HTTP -->
		<dependency>
		  <groupId>org.apache.httpcomponents</groupId>
		  <artifactId>httpclient</artifactId>
		  <version>4.5.3</version>
		</dependency>
		
		<!-- Jsoup HTTP -->
		<dependency>
			<groupId>org.jsoup</groupId>
			<artifactId>jsoup</artifactId>
			<version>1.9.1</version>
		</dependency>
		
		<!-- 图片Meta获取 -->
		<dependency>
			<groupId>com.drewnoakes</groupId>
			<artifactId>metadata-extractor</artifactId>
			<version>2.9.1</version>
		</dependency>
		<!-- 缩略图工具  -->
		<dependency>
			<groupId>net.coobird</groupId>
			<artifactId>thumbnailator</artifactId>
			<version>0.4.8</version>
		</dependency>
		<!-- 图片验证码生成  -->
		<dependency>
			<groupId>com.bladejava</groupId>
			<artifactId>blade-patchca</artifactId>
			<version>1.0.5</version>
		</dependency>
		
		<!-- jackson -->		
		<dependency>
		    <groupId>com.fasterxml.jackson.core</groupId>
		    <artifactId>jackson-core</artifactId>
		    <version>2.9.4</version>
		</dependency>
		<dependency>
		    <groupId>com.fasterxml.jackson.core</groupId>
		    <artifactId>jackson-databind</artifactId>
		    <version>2.9.5</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.dataformat/jackson-dataformat-xml -->
		<dependency>
		    <groupId>com.fasterxml.jackson.dataformat</groupId>
		    <artifactId>jackson-dataformat-xml</artifactId>
		    <version>2.9.5</version>
		</dependency>
		
		<!-- Java xml -->
		<dependency>
			<groupId>dom4j</groupId>
			<artifactId>dom4j</artifactId>
			<version>1.6.1</version>
		</dependency>
		
		<!-- XPath xml -->
		<dependency>
			<groupId>jaxen</groupId>
			<artifactId>jaxen</artifactId>
			<version>1.1.6</version>
		</dependency>
		
		<!-- Snake YAML -->
		<dependency>
			<groupId>org.yaml</groupId>
			<artifactId>snakeyaml</artifactId>
			<version>1.17</version>
		</dependency>
		
	
		<!-- Bean To Bean copy -->
		<dependency>
			<groupId>net.sf.dozer</groupId>
			<artifactId>dozer</artifactId>
			<version>${dozer.version}</version>
		</dependency>
		
		<!-- POI Office Tools -->
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi</artifactId>
			<version>${poi.version}</version>
			<exclusions>
				<exclusion>
					<artifactId>commons-codec</artifactId>
					<groupId>commons-codec</groupId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi-ooxml</artifactId>
			<version>${poi.version}</version>
		</dependency>
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi-ooxml-schemas</artifactId>
			<version>${poi.version}</version>
		</dependency>
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi-scratchpad</artifactId>
			<version>${poi.version}</version>
		</dependency>
		
		
		<!-- pinyin4j -->
		<dependency>
		    <groupId>com.belerweb</groupId>
		    <artifactId>pinyin4j</artifactId>
		    <version>2.5.0</version>
		</dependency>
		
		<!-- Apache Tools Ant Tar Zip  -->
		<dependency>
			<groupId>org.apache.ant</groupId>
			<artifactId>ant</artifactId>
			<version>1.9.7</version>
		</dependency>
		
		<!-- File MimeType ContentType -->
		<dependency>
			<groupId>net.sf.jmimemagic</groupId>
			<artifactId>jmimemagic</artifactId>
			<version>0.1.3</version>
			<exclusions>
				<exclusion>
					<groupId>xerces</groupId>
					<artifactId>xercesImpl</artifactId>
				</exclusion>
				<exclusion>
					<groupId>org.codehaus.jackson</groupId>
					<artifactId>jackson-xc</artifactId>
				</exclusion>
				<exclusion>
					<groupId>org.codehaus.jackson</groupId>
					<artifactId>jackson-jaxrs</artifactId>
				</exclusion>
				<exclusion>
					<artifactId>log4j</artifactId>
					<groupId>log4j</groupId>
				</exclusion>
			</exclusions>
		</dependency>
		
		  
  <!-- swagger -->  
	<dependency>    
	    <groupId>com.mangofactory</groupId>    
	    <artifactId>swagger-springmvc</artifactId>    
	    <version>1.0.2</version>    
	</dependency> 
	
	     <!-- hutool -->
      <dependency>
		    <groupId>cn.hutool</groupId>
		    <artifactId>hutool-all</artifactId>
		    <version>4.1.0</version>
	  </dependency>
	  
	    <dependency>
            <groupId>net.sf.ehcache</groupId>
            <artifactId>ehcache</artifactId>
            <version>2.10.4</version>
        </dependency>
		
		
		
	</dependencies>

	<build>
		<plugins>
		
			<!-- 指定编译版本 -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>
			
			
		</plugins>
				<finalName>${project.artifactId}</finalName>
	</build>
	
		<repositories>
	
		<repository>
			<id>aliyun-repos</id>
			<name>Aliyun Repository</name>
			<url>http://maven.aliyun.com/nexus/content/groups/public</url>
			<releases><enabled>true</enabled></releases>
			<snapshots><enabled>false</enabled></snapshots>
		</repository>
		
	</repositories>
	
	<pluginRepositories>
		
		<pluginRepository>
			<id>aliyun-repos</id>
			<name>Aliyun Repository</name>
			<url>http://maven.aliyun.com/nexus/content/groups/public</url>
			<releases><enabled>true</enabled></releases>
			<snapshots><enabled>false</enabled></snapshots>
		</pluginRepository>
	</pluginRepositories>        
</project>

 

 

二、编写实体

package com.blog.entity;

import java.io.Serializable;

import com.baomidou.mybatisplus.enums.IdType;
import java.util.Date;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableName;
import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.activerecord.Model;
import java.io.Serializable;

/**
 * <p>
 * 
 * </p>
 *
 * @author youcong123
 * @since 2018-07-22
 */
@TableName("user")
public class User extends Model<User> {

    private static final long serialVersionUID = 1L;

    /**
     * 用户主键
     */
    @TableId(value = "user_id", type = IdType.AUTO)
    private Integer userId;
    /**
     * 用户编码(登录账户) 手机号 邮箱号
     */
    @TableField("login_code")
    private String loginCode;
    /**
     * 用户名
     */
    @TableField("user_name")
    private String userName;
    /**
     * 密码
     */
    private String password;
    /**
     * 性别
     */
    private Integer sex;
    /**
     * 身份证
     */
    @TableField("identity_card")
    private String identityCard;
    /**
     * 创建时间
     */
    @TableField("create_time")
    private Date createTime;
    /**
     * 创建人
     */
    @TableField("create_by")
    private String createBy;
    /**
     * 更新时间
     */
    @TableField("update_time")
    private Date updateTime;
    /**
     * 更新人
     */
    @TableField("update_by")
    private String updateBy;
    /**
     * 状态:0注册新用户 1邮件认证用户 2管理员 3黑名单
     */
    private Integer status;


    public Integer getUserId() {
        return userId;
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
    }

    public String getLoginCode() {
        return loginCode;
    }

    public void setLoginCode(String loginCode) {
        this.loginCode = loginCode;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Integer getSex() {
        return sex;
    }

    public void setSex(Integer sex) {
        this.sex = sex;
    }

    public String getIdentityCard() {
        return identityCard;
    }

    public void setIdentityCard(String identityCard) {
        this.identityCard = identityCard;
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    public String getCreateBy() {
        return createBy;
    }

    public void setCreateBy(String createBy) {
        this.createBy = createBy;
    }

    public Date getUpdateTime() {
        return updateTime;
    }

    public void setUpdateTime(Date updateTime) {
        this.updateTime = updateTime;
    }

    public String getUpdateBy() {
        return updateBy;
    }

    public void setUpdateBy(String updateBy) {
        this.updateBy = updateBy;
    }

    public Integer getStatus() {
        return status;
    }

    public void setStatus(Integer status) {
        this.status = status;
    }

    @Override
    protected Serializable pkVal() {
        return this.userId;
    }

    @Override
    public String toString() {
        return "User{" +
        "userId=" + userId +
        ", loginCode=" + loginCode +
        ", userName=" + userName +
        ", password=" + password +
        ", sex=" + sex +
        ", identityCard=" + identityCard +
        ", createTime=" + createTime +
        ", createBy=" + createBy +
        ", updateTime=" + updateTime +
        ", updateBy=" + updateBy +
        ", status=" + status +
        "}";
    }
}

 

三、编写DAO

package com.blog.mapper;

import com.blog.entity.User;
import com.baomidou.mybatisplus.mapper.BaseMapper;

/**
 * <p>
 *  Mapper 接口
 * </p>
 *
 * @author youcong123
 * @since 2018-07-22
 */
public interface UserDao extends BaseMapper<User> {

}

 

四、编写业务接口类

package com.blog.service;

import com.blog.entity.User;
import com.baomidou.mybatisplus.service.IService;

/**
 * <p>
 *  服务类
 * </p>
 *
 * @author youcong123
 * @since 2018-07-22
 */
public interface UserService extends IService<User> {

	
	User getUserById(String userId);
	
	User login(String loginCode);
}

 

 

五、编写业务接口实现类

package com.blog.service.impl;

import com.blog.entity.User;
import com.blog.mapper.UserDao;
import com.blog.service.UserService;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;

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

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author youcong123
 * @since 2018-07-22
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserDao, User> implements UserService {

	@Autowired
	private UserDao userDao;
	@Override
	@Cacheable(value="cacheTest")
	public User getUserById(String userId) {
		
		return userDao.selectById(userId);
	}
	@Override
	public User login(String loginCode) {
	
		User user = new User();
		user.setLoginCode(loginCode);
		return userDao.selectOne(user);
	}

}

六、编写Controller

package com.blog.controller;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.blog.entity.User;
import com.blog.service.UserService;

import cn.hutool.json.JSONObject;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author youcong123
 * @since 2018-07-22
 */
@RestController
@RequestMapping("/user")
public class UserController {

	@Autowired
	private UserService userService;
	
	@GetMapping(value="getById",produces="application/json;charset=utf-8")
	public Object getById(String userId) {
		JSONObject json = new JSONObject();
		
		User user = userService.getUserById(userId);
		json.put("user", user);
		return user;
	}
	
	
}

 

 


七、编写DAO对应的XML

UserDao.xml

<?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="com.blog.mapper.UserDao">

    <!-- 通用查询映射结果 -->
    <resultMap id="BaseResultMap" type="com.blog.entity.User">
        <id column="user_id" property="userId" />
        <result column="login_code" property="loginCode" />
        <result column="user_name" property="userName" />
        <result column="password" property="password" />
        <result column="sex" property="sex" />
        <result column="identity_card" property="identityCard" />
        <result column="create_time" property="createTime" />
        <result column="create_by" property="createBy" />
        <result column="update_time" property="updateTime" />
        <result column="update_by" property="updateBy" />
        <result column="status" property="status" />
    </resultMap>

    <!-- 通用查询结果列 -->
    <sql id="Base_Column_List">
        user_id AS userId, login_code AS loginCode, user_name AS userName, password, sex, identity_card AS identityCard, create_time AS createTime, create_by AS createBy, update_time AS updateTime, update_by AS updateBy, status
    </sql>

</mapper>

 

八、编写配置文件

spring.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:util="http://www.springframework.org/schema/util"
       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 http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
    
    <!-- 引入属性文件 -->
    <context:property-placeholder location="classpath:config.properties"/>

    <!-- Service包(自动注入) -->
    <context:component-scan base-package="com.blog.service"/>

    <import resource="classpath:spring/spring-mybatis.xml"/>
</beans>

 

 

spring-mybatis.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    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:p="http://www.springframework.org/schema/p"
    xmlns:util="http://www.springframework.org/schema/util" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
    xmlns:cache="http://www.springframework.org/schema/cache"
    xsi:schemaLocation="  
    http://www.springframework.org/schema/context  
    http://www.springframework.org/schema/context/spring-context.xsd  
    http://www.springframework.org/schema/beans  
    http://www.springframework.org/schema/beans/spring-beans.xsd  
    http://www.springframework.org/schema/tx  
    http://www.springframework.org/schema/tx/spring-tx.xsd  
    http://www.springframework.org/schema/jdbc  
    http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd  
    http://www.springframework.org/schema/cache  
    http://www.springframework.org/schema/cache/spring-cache-3.1.xsd  
    http://www.springframework.org/schema/aop  
    http://www.springframework.org/schema/aop/spring-aop.xsd  
    http://www.springframework.org/schema/util  
    http://www.springframework.org/schema/util/spring-util.xsd">

    <!-- 应用spring-cache注解功能 -->
    <cache:annotation-driven cache-manager="cacheManager" />  

    <!-- 配置数据源 -->
    <bean name="defaultDataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
        <property name="url" value="${jdbc_url}"/>
        <property name="username" value="${jdbc_username}"/>
        <property name="password" value="${jdbc_password}"/>

        <!-- 初始化连接大小 -->
        <property name="initialSize" value="0"/>
        <!-- 连接池最大使用连接数量 -->
        <property name="maxActive" value="20"/>
        <!-- 连接池最大空闲 -->
        <property name="maxIdle" value="20"/>
        <!-- 连接池最小空闲 -->
        <property name="minIdle" value="0"/>
        <!-- 获取连接最大等待时间 -->
        <property name="maxWait" value="60000"/>

        <property name="validationQuery" value="${validationQuery}"/>
        <property name="testOnBorrow" value="false"/>
        <property name="testOnReturn" value="false"/>
        <property name="testWhileIdle" value="true"/>

        <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
        <property name="timeBetweenEvictionRunsMillis" value="60000"/>
        <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
        <property name="minEvictableIdleTimeMillis" value="25200000"/>

        <!-- 打开removeAbandoned功能 -->
        <property name="removeAbandoned" value="true"/>
        <!-- 1800秒,也就是30分钟 -->
        <property name="removeAbandonedTimeout" value="1800"/>
        <!-- 关闭abanded连接时输出错误日志 -->
        <property name="logAbandoned" value="true"/>

        <!-- 监控数据库 -->
        <property name="filters" value="mergeStat"/>
    </bean>
    
   <bean id="druidDynamicDataSource" class="com.blog.datasource.DruidDynamicDataSource">
		<property name="defaultTargetDataSource" ref="defaultDataSource" />
        <property name="targetDataSources">
            <map>
                <entry key="defaultDataSource" value-ref="defaultDataSource"/>
                <!-- 这里还可以加多个dataSource -->
            </map>
        </property>
    </bean>    
    <!-- Spring整合Mybatis,更多查看文档:http://mp.baomidou.com -->
    <bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean">
       <property name="dataSource" ref="druidDynamicDataSource" />
        <!-- 自动扫描Mapping.xml文件 -->
        <property name="mapperLocations" value="classpath:mybatis/system/*.xml"/>
        <property name="configLocation" value="classpath:mybatis/mybatis-config.xml"/>
        <property name="typeAliasesPackage" value="com.blog.entity"/>
        <property name="plugins">
            <array>
                <!-- 分页插件配置 -->
                <bean id="paginationInterceptor" class="com.baomidou.mybatisplus.plugins.PaginationInterceptor">
                </bean>
            </array>
        </property>
	    <!-- 全局配置注入 -->
	    <property name="globalConfig" ref="globalConfig" />
	</bean>
	<bean id="globalConfig" class="com.baomidou.mybatisplus.entity.GlobalConfiguration">
	    <!--
			AUTO->`0`("数据库ID自增")
		 	INPUT->`1`(用户输入ID")
			ID_WORKER->`2`("全局唯一ID")
			UUID->`3`("全局唯一ID")
		-->
	    <property name="idType" value="2" />
		<!--
			MYSQL->`mysql`
			ORACLE->`oracle`
			DB2->`db2`
			H2->`h2`
			HSQL->`hsql`
			SQLITE->`sqlite`
			POSTGRE->`postgresql`
			SQLSERVER2005->`sqlserver2005`
			SQLSERVER->`sqlserver`
		-->
		<!-- Oracle需要添加该项 -->
	    <!-- <property name="dbType" value="oracle" /> -->
	    <!-- 全局表为下划线命名设置 true -->
	    <!-- <property name="dbColumnUnderline" value="true" /> -->
<!--         <property name="metaObjectHandler">
            <bean class="com.lms.common.MyMetaObjectHandler" />
        </property> -->
	</bean>

    <!-- MyBatis 动态扫描  -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.blog.mapper"/>
    </bean>

    <!-- 配置事务管理 -->
    <bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="druidDynamicDataSource"/>
    </bean>

    <!-- 事务管理 属性 -->
    <tx:advice id="transactionAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="add*" propagation="REQUIRED"/>
            <tx:method name="append*" propagation="REQUIRED"/>
            <tx:method name="save*" propagation="REQUIRED"/>
            <tx:method name="update*" propagation="REQUIRED"/>
            <tx:method name="modify*" propagation="REQUIRED"/>
            <tx:method name="edit*" propagation="REQUIRED"/>
            <tx:method name="insert*" propagation="REQUIRED"/>
            <tx:method name="delete*" propagation="REQUIRED"/>
            <tx:method name="remove*" propagation="REQUIRED"/>
            <tx:method name="repair" propagation="REQUIRED"/>

            <tx:method name="get*" propagation="REQUIRED" read-only="true"/>
            <tx:method name="find*" propagation="REQUIRED" read-only="true"/>
            <tx:method name="load*" propagation="REQUIRED" read-only="true"/>
            <tx:method name="search*" propagation="REQUIRED" read-only="true"/>
            <tx:method name="datagrid*" propagation="REQUIRED" read-only="true"/>

            <tx:method name="*" propagation="REQUIRED" read-only="true"/>
        </tx:attributes>
    </tx:advice>

    <!-- 配置切面 -->
    <aop:config>
        <aop:pointcut id="transactionPointcut" expression="execution(* com.blog.service..*.*(..))"/>
        <aop:advisor pointcut-ref="transactionPointcut" advice-ref="transactionAdvice"/>
    </aop:config>
    
     <!-- 配置ehcache管理器-->

    <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-setting.xml"></property>  
    </bean>  

</beans>

 

spring-mvc.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:mvc="http://www.springframework.org/schema/mvc"
       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 http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
      <!-- Controller包(自动注入) -->
    <context:component-scan base-package="com.blog.controller"/>

    <mvc:default-servlet-handler/>
    
     <!-- FastJson注入 -->
    <mvc:annotation-driven>
        <mvc:message-converters register-defaults="true">
     
            <bean id="fastJsonHttpMessageConverter"
                  class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                     
                        <value>text/html;charset=UTF-8</value>
                        <value>application/json;charset=UTF-8</value>
                    </list>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>



     

    <!-- 上传限制 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 上传文件大小限制为31M,31*1024*1024 -->
        <property name="maxUploadSize" value="32505856"/>
    </bean>
    

    
</beans>

 

 

config.properties

validationQuery=SELECT 1
jdbc_url=jdbc:mysql://localhost:3306/blog_test?useUnicode=true&characterEncoding=UTF-8
jdbc_username=root
jdbc_password=1234

 

ehcache-setting.xml

<?xml version="1.0" encoding="UTF-8"?>
<ehcache>
    <!-- 指定一个文件目录,当EhCache把数据写到硬盘上时,将把数据写到这个文件目录下 -->
<!--     <diskStore path="D://cache//java-cache"/> -->
 <diskStore path="java.io.tmpdir"/>  
    <!-- 设定缓存的默认数据过期策略 -->
    <defaultCache
            maxElementsInMemory="10000" 
            eternal="false" 
            overflowToDisk="true"
            timeToIdleSeconds="10"
            timeToLiveSeconds="20"
            diskPersistent="false"
            diskExpiryThreadIntervalSeconds="120"/>

    <cache name="cacheTest"
        maxElementsInMemory="1000"
        eternal="false"
        overflowToDisk="true"
        timeToIdleSeconds="100"
        timeToLiveSeconds="200"/>

</ehcache>

 

 

关于diskstore配置说明:

1、diskStore元素是可选的,非必须的。如果不使用磁盘存储,只需要将diskStore注释掉即可;如果使用,需要在ehcache.xml文件中的ehcahce元素下的定义一个diskStore元素并指定其path属性。
2、由diskStore元素是定义在ehcache元素下我们看出diskStore在CacheManager范围内是共享的,其是线程安全的
3、对于任何缓存,如果你已经激活了overflowToDisk或diskPersistent,就要配置磁盘存储器。
(关于overflowToDisk或diskPersistent的配置,详见配置文件ehcache.xml详解(1) )
4、DiskStore中驱除元素跟MemoryStore中驱除元素的规则是不一样的。当往DiskStore中添加元素且此时DiskStore中的容量已经超出限制时将采用LFU(最不常用)驱除规则将对应的元素进行删除,而且该驱除规则是不可配置的(通过cache中的diskExpiryThreadIntervalSeconds属性完成)
5、path属性如果是下述Java系统属性之一,他将会被运行中的VM中的值替换。为了向后兼容,这些应该被特别规定,而不会被${token}替换语法封闭。
6、path属性可以配置的目录有:
    user.home(用户的家目录)
    user.dir(用户当前的工作目录)
    java.io.tmpdir(默认的临时目录)
    ehcache.disk.store.dir(ehcache的配置目录)
    绝对路径(如:d://javastore)

 

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD SQL Map Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<!--
 |   plugins在配置文件中的位置必须符合要求,否则会报错,顺序如下:
 |   properties?, settings?,
 |   typeAliases?, typeHandlers?,
 |   objectFactory?,objectWrapperFactory?,
 |   plugins?,
 |   environments?, databaseIdProvider?, mappers?
 |-->
<configuration>
    <!--
     | 全局配置设置
     |
     | 可配置选项                   默认值,     描述
     |
     | aggressiveLazyLoading       true,     当设置为‘true’的时候,懒加载的对象可能被任何懒属性全部加载。否则,每个属性都按需加载。
     | multipleResultSetsEnabled   true,     允许和不允许单条语句返回多个数据集(取决于驱动需求)
     | useColumnLabel              true,     使用列标签代替列名称。不同的驱动器有不同的作法。参考一下驱动器文档,或者用这两个不同的选项进行测试一下。
     | useGeneratedKeys            false,    允许JDBC 生成主键。需要驱动器支持。如果设为了true,这个设置将强制使用被生成的主键,有一些驱动器不兼容不过仍然可以执行。
     | autoMappingBehavior         PARTIAL,  指定MyBatis 是否并且如何来自动映射数据表字段与对象的属性。PARTIAL将只自动映射简单的,没有嵌套的结果。FULL 将自动映射所有复杂的结果。
     | defaultExecutorType         SIMPLE,   配置和设定执行器,SIMPLE 执行器执行其它语句。REUSE 执行器可能重复使用prepared statements 语句,BATCH执行器可以重复执行语句和批量更新。
     | defaultStatementTimeout     null,     设置一个时限,以决定让驱动器等待数据库回应的多长时间为超时
     | -->
    <settings>
        <!-- 这个配置使全局的映射器启用或禁用缓存 -->
        <setting name="cacheEnabled" value="true"/>
        <!-- 全局启用或禁用延迟加载。当禁用时,所有关联对象都会即时加载 -->
        <setting name="lazyLoadingEnabled" value="true"/>
        <setting name="multipleResultSetsEnabled" value="true"/>
        <setting name="useColumnLabel" value="true"/>
        <setting name="defaultExecutorType" value="REUSE"/>
        <setting name="defaultStatementTimeout" value="25000"/>
    </settings>
    
    <plugins>
    
        <!-- SQL 执行分析拦截器 stopProceed 发现全表执行 delete update 是否停止运行 -->
        <plugin interceptor="com.baomidou.mybatisplus.plugins.SqlExplainInterceptor">
            <property name="stopProceed" value="false" />
        </plugin>
        
          <!-- SQL 执行性能分析,开发环境使用,线上不推荐。 maxTime 指的是 sql 最大执行时长 -->
        <plugin interceptor="com.baomidou.mybatisplus.plugins.PerformanceInterceptor">
            <property name="maxTime" value="100" />
            <!--SQL是否格式化 默认false-->
            <property name="format" value="true" />
        </plugin>

    
    </plugins>

</configuration>

 

 

log4j.properties

#config root logger
log4j.rootLogger = INFO,system.out
log4j.appender.system.out=org.apache.log4j.ConsoleAppender
log4j.appender.system.out.layout=org.apache.log4j.PatternLayout
log4j.appender.system.out.layout.ConversionPattern=[Log]%-d{yyyy-MM-dd HH:mm:ss} %5p[%F:%L]:%m%n
#log4j.appender.system.out.layout.ConversionPattern=[Log] %5p[%F:%L]:%m%n

#config this Project.file logger
log4j.logger.thisProject.file=INFO,thisProject.file.out
log4j.appender.thisProject.file.out=org.apache.log4j.DailyRollingFileAppender
log4j.appender.thisProject.file.out.File=pmslogout.log
log4j.appender.thisProject.file.out.layout=org.apache.log4j.PatternLayout
log4j.appender.thisProject.file.out.layout.ConversionPattern=[Log]%-d{yyyy-MM-dd HH:mm:ss} %5p[%F:%L]:%m%n
log4j.appender.thisProject.file.append=true

 

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
  <display-name>Blog</display-name>
  <!-- 欢迎页 -->
  <welcome-file-list>
       <welcome-file>views/login.html</welcome-file>
  </welcome-file-list>
  

  <!-- 加载配置文件 -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring/spring.xml</param-value>
  </context-param>
  
  
  <!-- 字符过滤器 拦截所有 -->
  <filter>
    <filter-name>encodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>


  <!-- 上下文监听 -->
  <listener>
    <description>Spring监听器</description>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 
  </listener>


  <!-- 前端控制器 拦截 -->
  <servlet>
    <servlet-name>SpringMVC</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <description>SpringMVC</description>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring/spring-mvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>SpringMVC</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  <!-- session过期时间 -->
  <session-config>
    <session-timeout>30</session-timeout>
  </session-config>
  
</web-app>

 

 

九、运行项目,如果控制台五报错,就通过PostMan接口测试

PostMan可运行多次 发现控制台始终都只打印一次就表示缓存成功

 

 


posted @ 2018-11-08 19:17  挑战者V  阅读(1641)  评论(0编辑  收藏  举报