1.首先创建数据库文件,这里使用MySQL
CREATE TABLE `sveell_student` ( `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键,自动递增', `name` varchar(32) CHARACTER SET utf8 COLLATE utf8_croatian_ci NULL DEFAULT NULL COMMENT '姓名', `sex` char(1) CHARACTER SET utf8 COLLATE utf8_croatian_ci NULL DEFAULT NULL COMMENT '性别:0:女 1:男', `birthday` date NULL DEFAULT NULL COMMENT '出生日期', `picture` varchar(255) CHARACTER SET utf8 COLLATE utf8_croatian_ci NULL DEFAULT NULL COMMENT '照片', `hobby` varchar(36) CHARACTER SET utf8 COLLATE utf8_croatian_ci NULL DEFAULT NULL COMMENT '爱好:1.足球2.篮球3.排球4.乒乓球5.音乐6.舞蹈', `phone` char(11) CHARACTER SET utf8 COLLATE utf8_croatian_ci NULL DEFAULT NULL COMMENT '电话', `address` varchar(255) CHARACTER SET utf8 COLLATE utf8_croatian_ci NULL DEFAULT NULL COMMENT '家庭地址', `introduce` varchar(255) CHARACTER SET utf8 COLLATE utf8_croatian_ci NULL DEFAULT NULL COMMENT '自我介绍', `create_time` varchar(255) CHARACTER SET utf8 COLLATE utf8_croatian_ci NULL DEFAULT '0000-00-00 00:00:00' COMMENT '创建时间', `state` char(1) CHARACTER SET utf8 COLLATE utf8_croatian_ci NULL DEFAULT '0' COMMENT '状态: 0:正常 1:已删除', `spare` varchar(32) CHARACTER SET utf8 COLLATE utf8_croatian_ci NULL DEFAULT NULL COMMENT '备用字段', PRIMARY KEY (`id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 27 CHARACTER SET = utf8 COLLATE = utf8_croatian_ci ROW_FORMAT = Dynamic; SET FOREIGN_KEY_CHECKS = 1;2.创建一个SpringBoot项目,加入pom依赖
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.0.1</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>2.2.0</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.16.20</version> <scope>provided</scope> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.1.41</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> <!--数据库连接池代替C3P0--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.22</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>com.fasterxml.jackson.datatype</groupId> <artifactId>jackson-datatype-guava</artifactId> <version>2.9.8</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.6</version> </dependency> <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache</artifactId> <version>2.10.3</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency> </dependencies>3.配置application.yml文件
# 配置访问端口 server: port: 8080 #配置项目路径 servlet: context-path: / # 配置模板引擎 thymeleaf: # 是否启用模板缓存 cache: false # 应用于模板的模板模式,参考TemplateMode 枚举 mode: HTML5 # 模板文件编码 encoding: UTF-8 # 构建URL时预先查看视图名称的前缀 prefix: classpath:/templates/ # 在构建URL时附加到视图名称的后缀 suffix: .html # 文件解析格式 content-type: text/html resources: # 指定静态资源的路径 static-locations: classpath:/static/,classpath:/templates/,classpath:/public/ # 默认值为 classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/ static-path-pattern: /** # mysql配置 spring: # 运行的环境 dev:开发环境|test:测试环境|prod:生产环境 profiles: active: dev datasource: url: jdbc:mysql://127.0.0.1:3306/Student?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC username: root password: oywh type: com.alibaba.druid.pool.DruidDataSource driver-class-name: com.mysql.cj.jdbc.Driver filters: stat #连接池的最大值,同一时间可以从池分配的最多连接数量,0时无限制 maxActive: 20 #连接初始值,连接池启动时创建的连接数量的初始值 initialSize: 1 maxWait: 60000 #最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时来不及申请 minIdle: 1 timeBetweenEvictionRunsMillis: 60000 minEvictableIdleTimeMillis: 300000 validationQuery: select 'x' testWhileIdle: true testOnBorrow: false testOnReturn: false #是否对已备语句进行池管理(布尔值),是否对PreparedStatement进行缓存 poolPreparedStatements: true maxOpenPreparedStatements: 20 jackson: date-format: yyyy-MM-dd HH:mm:ss #time-zone: GMT+8 servlet: multipart: enabled: true #配置文件传输 file-size-threshold: 0 #单个数据的大小 max-file-size: 100MB #总数据的大小 max-request-size: 100MB #配置ehcache配置文件 cache: ehcache: config: classpath:ehcache.xml type: ehcache #日志打印级别 debug: false logging: level: top.denghuolanshan.admin.dao: DEBUG file: F:\student.log mybatis-plus: type-aliases-package: cn.svell.entity #config-location: classpath*:/mapper/**Mapper.xml global-config: #主键类型 0:"数据库ID自增", 1:"用户输入ID",2:"全局唯一ID (数字类型唯一ID)", 3:"全局唯一ID UUID"; id-type: 0 #字段策略 0:"忽略判断",1:"非 NULL 判断"),2:"非空判断" field-strategy: 2 #驼峰下划线转换 db-column-underline: true #刷新mapper 调试神器 refresh-mapper: true #数据库大写下划线转换 capital-mode: true #逻辑删除配置(下面3个配置) logic-delete-value: 0 logic-not-delete-value: 1 #自定义SQL注入器 #sql-injector: com.baomidou.mybatisplus.mapper.LogicSqlInjector configuration: map-underscore-to-camel-case: true cache-enabled: false4.在resources下加入ehcache.xml配置文件,内容如下
<?xml version="1.0" encoding="UTF-8"?> <ehcache> <!-- 磁盘存储:将缓存中暂时不使用的对象,转移到硬盘,类似于Windows系统的虚拟内存 path:指定在硬盘上存储对象的路径 --> <diskStore path="G:\ehcache" /> <!-- defaultCache:默认的缓存配置信息,如果不加特殊说明,则所有对象按照此配置项处理 maxElementsInMemory:设置了缓存的上限,最多存储多少个记录对象 eternal:代表对象是否永不过期 overflowToDisk:当内存中Element数量达到maxElementsInMemory时,Ehcache将会Element写到磁盘中 --> <defaultCache maxElementsInMemory="100" eternal="true" overflowToDisk="true"/> <!-- maxElementsInMemory设置成1,overflowToDisk设置成true,只要有一个缓存元素,就直接存到硬盘上去 eternal设置成true,代表对象永久有效 maxElementsOnDisk设置成0 表示硬盘中最大缓存对象数无限大 diskPersistent设置成true表示缓存虚拟机重启期数据 --> <cache name="a" maxElementsInMemory="1" eternal="true" overflowToDisk="true" maxElementsOnDisk="0" diskPersistent="true"/> </ehcache>5.因为涉及到了前端,我这里不给代码了,因为页面,代码太多,我会在文末放置项目链接的,数据持久层我用的是MyBatisPlus,实体类,dao接口和controller不在写了,但有几个需要之一的地方
1.SpringBoot启动类上要添加一个@EnableCaching注解 2.实体类要序列化,实现Serializable即可6.直接说Service,因为缓存是用在Service方法上的,我看网上有些说注解写在dao接口上,我没有测试,但如果使用MyBatisPlus的话,基本的CRUD是没有办法加注解的
package cn.svell.service.impl; import cn.svell.entity.Student; import cn.svell.mappeer.StudentMapper; import cn.svell.service.StudentService; import cn.svell.utils.DataUtil; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.Date; import java.util.List; /** * @ClassName StudentServiceImpl * @Description TODO * @Author 小欧 * @Date 2019/7/19 21:42 * @Version 1.0 **/ @Service public class StudentServiceImpl implements StudentService { @Resource private StudentMapper studentMapper; @Cacheable(value="a") @Override public List<Student> getStudentList() { List<Student> studentList = null; studentList = studentMapper.findAll(); String result = ""; for (Student student : studentList) { // 因为该字段使用的Date类型所以需要格式化日期 String birthday = DataUtil.formatDatetoString(student.getBirthday(), "yyyy-MM-dd"); student.setBirth(birthday); String hobby = student.getHobby(); if (hobby==null){ // 写不写无所谓 student.setHobby("无"); }else if (hobby.contains("1")||hobby.contains("2")||hobby.contains("3")||hobby.contains("4")||hobby.contains("5")||hobby.contains("6")){ // 因为前端不是很精通所以爱好数据直接在这里处理了,解决方案不是很好 hobby = judgmentType(result, student); student.setHobby(hobby); } } return studentList; } @CacheEvict(value="a",allEntries=true) @Override public int deleteStudent(Integer id) { return studentMapper.updateStateById(id); } @CacheEvict(value="a",allEntries=true) @Override public int saveStudent(Student student) throws Exception { String birth = student.getBirth(); Date date = DataUtil.StringFormatDate(birth, "yyyy-MM-dd"); student.setBirthday(date); student.setCreateTime(DataUtil.formatDatetoString(new Date(),"yyyy-MM-dd HH:mm:ss")); if (student.getId() == null){ // 添加 Integer add = studentMapper.insert(student); if(add == 1){ return add; } throw new Exception(); } // 修改 Integer edit = studentMapper.updateAllColumnById(student); if(edit == 1){ return edit; } return 0; } /*** * 直接在后台根据前端的value值转换成了对应的文字, * 因为StringBuffer不能传入空值,所以我采用类比较消耗内存的“+”号连接符 * @param result * @param student * @return */ private String judgmentType(String result, Student student) { String hobby = student.getHobby(); if (hobby.contains("1")){ result = result + "足球 "; } if (hobby.contains("2")){ result = result + "篮球 "; } if (hobby.contains("3")){ result = result + "排球 "; } if (hobby.contains("4")){ result = result + "乒乓球 "; }if (hobby.contains("5")){ result = result + "音乐 "; } if (hobby.contains("6")){ result = result + "舞蹈 "; } return result; } }7.直接在service查询方法上添加@Cacheable(value=“a”)注解就可以了,而删除,修改,添加后要更新缓存,则添加注解@CacheEvict(value=“a”,allEntries=true)即可。
8.最后附上项目地址链接:https://pan.baidu.com/s/1LR5QZL2dZlLoDl2BtNLUVA 提取码:fxzh
