目录结构:
pom.xml文件:
<?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.roncoo.education</groupId>
<artifactId>spring-boot-demo-19-1</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>spring-boot-demo-19-1</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.0.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>2.1.4</version>
</dependency>
<!-- 数据库 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- caching -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
application.properties文件:
#开发环境
server.port=8080
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
# JPA
spring.jpa.hibernate.ddl-auto= update
spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect
#显示sql语句
spring.jpa.show-sql=true
#spring.cache.type=ehcache
spring.cache.ehcache.config=classpath:config/ehcache.xml
ehcache.xml文件:
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="ehcache.xsd">
<cache name="roncooCache"
eternal="false"
maxEntriesLocalHeap="0"
timeToIdleSeconds="200"></cache>
<!-- eternal:true表示对象永不过期,此时会忽略timeToIdleSeconds和timeToLiveSeconds属性,默认为false -->
<!-- maxEntriesLocalHeap:堆内存中最大缓存对象数,0没有限制 -->
<!-- timeToIdleSeconds: 设定允许对象处于空闲状态的最长时间,以秒为单位。当对象自从最近一次被访问后,如果处于空闲状态的时间超过了timeToIdleSeconds属性值,这个对象就会过期,EHCache将把它从缓存中清空。只有当eternal属性为false,该属性才有效。如果该属性值为0,则表示对象可以无限期地处于空闲状态 -->
</ehcache>
package com.roncoo.example.uitl;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
/**
* @author
*/
@WebFilter(filterName = "customFilter", urlPatterns = "/*")
public class CustomFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("init filter");
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
System.out.println("do filter...");
chain.doFilter(request, response);
}
@Override
public void destroy() {
System.out.println("destroy filter");
}
}
package com.roncoo.example.uitl;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
/**
* @author
*/
@WebListener
public class CustomListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
System.out.println("contextInitialized");
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
System.out.println("contextDestroyed");
}
}
package com.roncoo.example.uitl;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 自定义servlet
*
* @author
*/
@WebServlet(name = "customServlet", urlPatterns = "/roncoo")
public class CustomServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("servlet get method");
doPost(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("servlet post method");
response.getWriter().write("hello world");
response.flushBuffer();
}
}
package com.roncoo.example.dao;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import com.roncoo.example.bean.RoncooUserLog;
public interface RoncooUserLogDao extends JpaRepository<RoncooUserLog, Integer>{
@Query(value="select u from RoncooUserLog u where u.userName=?1")
RoncooUserLog findByUserName(String string);
RoncooUserLog findByUserNameAndUserIp(String string, String ip);
Page<RoncooUserLog> findByUserName(String string, Pageable pageable);
}
package com.roncoo.example.controller;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.roncoo.example.bean.RoncooUserLog;
import com.roncoo.example.cache.RoncooUserLogCache;
@RestController
@RequestMapping("/api")
public class ApiController {
@Autowired
private RoncooUserLogCache roncooUserLogCache;
@CrossOrigin(origins = "http://localhost:8080")
@RequestMapping(value = "/get", method = RequestMethod.POST)
public HashMap<String, Object> get(@RequestParam String name) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("title", "hello world");
map.put("name", name);
return map;
}
@RequestMapping(value = "/select", method = RequestMethod.GET)
public RoncooUserLog get(@RequestParam(defaultValue = "1") Integer id) {
return roncooUserLogCache.selectById(id);
}
@RequestMapping(value = "/update", method = RequestMethod.GET)
public RoncooUserLog update(@RequestParam(defaultValue = "1") Integer id) {
RoncooUserLog bean = roncooUserLogCache.selectById(id);
bean.setUserName("测试");
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateString = formatter.format(new Date());
bean.setCreateTime(dateString);
roncooUserLogCache.updateById(bean);
return bean;
}
@RequestMapping(value = "/del", method = RequestMethod.GET)
public String del(@RequestParam(defaultValue = "1") Integer id) {
return roncooUserLogCache.deleteById(id);
}
}
package com.roncoo.example.cache;
import com.roncoo.example.bean.RoncooUserLog;
/**
* @author
*/
public interface RoncooUserLogCache {
/**
* 查询
*
* @param id
* @return
*/
RoncooUserLog selectById(Integer id);
/**
* 更新
*
* @param roncooUserLog
* @return
*/
RoncooUserLog updateById(RoncooUserLog roncooUserLog);
/**
* 删除
*
* @param id
* @return
*/
String deleteById(Integer id);
}
package com.roncoo.example.cache.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Repository;
import com.roncoo.example.bean.RoncooUserLog;
import com.roncoo.example.cache.RoncooUserLogCache;
import com.roncoo.example.dao.RoncooUserLogDao;
/**
* @author
*/
@CacheConfig(cacheNames = "roncooCache")
@Repository
public class RoncooUserLogCacheImpl implements RoncooUserLogCache {
@Autowired
private RoncooUserLogDao roncooUserLogDao;
//表示该方法支持缓存,Spring会在其被调用后将其返回值缓存起来,以保证下次利用同样的参数来执行该方法时可以直接从缓存中获取结果,
//而不需要再次执行该方法。
@Cacheable(key = "#p0")
@Override
public RoncooUserLog selectById(Integer id) {
System.out.println("查询功能,缓存找不到,直接读库, id=" + id);
return roncooUserLogDao.findOne(id);
}
//@CachePut标注的方法在执行前不会去检查缓存中是否存在之前执行过的结果,而是每次都会执行该方法,并将执行结果以键值对的形式存入指定的缓存中。
@CachePut(key = "#p0")
@Override
public RoncooUserLog updateById(RoncooUserLog roncooUserLog) {
System.out.println("更新功能,更新缓存,直接写库, id=" + roncooUserLog);
return roncooUserLogDao.save(roncooUserLog);
}
// @CacheEvict是用来标注在需要清除缓存元素的方法或类上的。当标记在一个类上时表示其中所有的方法的执行都会触发缓存的清除操作。
@CacheEvict(key = "#p0")
@Override
public String deleteById(Integer id) {
System.out.println("删除功能,删除缓存,直接写库, id=" + id);
return "清空缓存成功";
}
}
package com.roncoo.example.bean;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity
public class RoncooUserLog {
@Id
@GeneratedValue
private Integer id;
@Column
private String createTime;
@Column
private String userName;
@Column
private String userIp;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getCreateTime() {
return createTime;
}
public void setCreateTime(String createTime) {
this.createTime = createTime;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserIp() {
return userIp;
}
public void setUserIp(String userIp) {
this.userIp = userIp;
}
@Override
public String toString() {
return "RoncooUserLog [id=" + id + ", createTime=" + createTime + ", userName=" + userName + ", userIp=" + userIp + "]";
}
}
package com.roncoo.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.cache.annotation.EnableCaching;
@EnableCaching
@ServletComponentScan
@SpringBootApplication
public class SpringBootDemo201Application {
public static void main(String[] args) {
SpringApplication.run(SpringBootDemo201Application.class, args);
}
}
访问链接:http://localhost:8080/api/select
http://localhost:8080/api/update
这里就是将数据保存到缓存中,然后更新了数据也得更新缓存。后面再查询直接读取缓存中的数据,不读库了。