关于java:使用Spring-Boot-MyBatis-FreeMarker-Ehcache进行web开发

5次阅读

共计 8597 个字符,预计需要花费 22 分钟才能阅读完成。

文章原文:https://tlanyan.pp.ua/spring-boot-mybatis-freemarker-ehcache-web-development/

之前做的 Java 我的项目都是接手自他人,本人没有独立开发过。这几天抽空钻研了一下 Spring Boot 做 web 开发,本文用作记录和参考应用。

筹备工作

  1. 装置 InteliJ IDEA;InteliJ IDEA 基本上是 Java 和安卓开发必备工具,社区版可收费应用;
  2. 装置 Mysql 或 Mariadb 数据库。

应用 Spring Boot + MyBatis + FreeMarker 进行 web 开发

创立 Spring Boot 我的项目

1. 关上 IDEA,创立新我的项目,在疏导对话框当选“Spring Initializr”,并自定义项目名称、包名,抉择 Java SDK 和版本等:

2. 抉择 Spring Boot DevTools、Lombok、Spring Web、Freemarker、MyBatis 和 MySQL 这几个包:

生成的 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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.4.5</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.tlanyan</groupId>
<artifactId>springboot</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot</name>
<description>Demo project for Spring Boot</description>
<properties>
    <java.version>1.8</java.version>
</properties>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-freemarker</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.1.4</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </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>
            <configuration>
                <excludes>
                    <exclude>
                        <groupId>org.projectlombok</groupId>
                        <artifactId>lombok</artifactId>
                    </exclude>
                </excludes>
            </configuration>
        </plugin>
    </plugins>
</build>

</project>

3. 因为没有配置数据库等,我的项目此时还无奈启动。在根目录下创立 application.yml 文件,输出如下内容:

server:
port: 9000

spring:
freemarker:

template-loader-path: classpath:/templates
cache: true
suffix: .ftl

datasource:

url: jdbc:mysql://127.0.0.1:3306/demo?characterEncoding=utf-8&useSSL=false&useUnicode=true
username: root
password: password
driver-class-name: com.mysql.cj.jdbc.Driver

mybatis:
mapper-locations: classpath:/templates/mapper/*Mapper.xml # mapper 文件地位
type-aliases-package: com.tlanyan.springboot.entity

如果相熟 properties 文件的写法,能够间接编辑 src/resources 文件夹下的 application.properties 文件

此时我的项目能够失常运行(Run -> Run “SpringbootApplication”)。

Spring Boot 托管动态文件

动态资源放到 src/resources/static 目录下即可被拜访到(增加新文件后需从新运行程序):

除了默认创立的 static 目录,动态资源文件还能够寄存到 public、resources 和 META-INF/resouces 目录下。

Spring Boot + MyBatis + Spring MVC + FreeMarker

MyBatis 是一款优良的长久层框架,它反对自定义 SQL、存储过程以及高级映射。MyBatis 罢黜了简直所有的 JDBC 代码以及设置参数和获取后果集的工作。MyBatis 能够通过简略的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,一般老式 Java 对象)为数据库中的记录。

首先创立数据库表对应的实体类:

package com.tlanyan.springboot.entity;

import lombok.Data;

import java.io.Serializable;

@Data
public class User implements Serializable {

private Integer id;
private String name;

}

而后创立 Mapper 接口:

package com.tlanyan.springboot.mapper;

import com.tlanyan.springboot.entity.User;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;

@Mapper
public interface UserMapper {

public User findById(Integer id);

public List getAll();

}

以及在 templates/mapper 目录下创立 UserMapper.xml 文件(mapper 文件需放到配置文件中的指定目录下,templates 中的文件会被主动打包,因而咱们抉择这个地位):

<?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.tlanyan.springboot.mapper.UserMapper”>

<select id="findById" resultType="com.tlanyan.springboot.entity.User">
    SELECT * from user WHERE id = #{id}
</select>
<select id="getAll" resultType="com.tlanyan.springboot.entity.User">
    select * from user
</select>

</mapper>

接下来编写 service 层:

package com.tlanyan.springboot.service;

import com.tlanyan.springboot.entity.User;

import java.util.List;

public interface UserService {

public User findById(Integer id);

public List<User> getAll();

}

以及其实现:

package com.tlanyan.springboot.service.impl;

import com.tlanyan.springboot.entity.User;
import com.tlanyan.springboot.mapper.UserMapper;
import com.tlanyan.springboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

@Autowired
private UserMapper userMapper;

@Override
public User findById(Integer id) {return userMapper.findById(id);
}

@Override
public List<User> getAll() {return userMapper.getAll();
}

}

而后 controller 层:

package com.tlanyan.springboot.controller;

import com.tlanyan.springboot.entity.User;
import com.tlanyan.springboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
public class UserController {

@Autowired
private UserService userService;

@RequestMapping("/user/list")
public String List(Model model) {List<User> users = userService.getAll();
    model.addAttribute("users", users);

    return "user/index";
}

@RequestMapping("/user/{id}")
public String view(@PathVariable("id") Integer id, Model model) {User user = userService.findById(id);
    model.addAttribute("user", user);

    return "user/view";
}

}

最初编写 Freemarker 模板。在 resources/templates 文件夹下创立 user 文件夹,新建 index.ftl 输出下列内容:

<h1>User List</h1>

<ul>

<#list users as user>
    <li>ID: ${user.id}, name: ${user.name}</li>
</#list>

</ul>

以及 view.ftl:

<h1>User ID: ${user.id}, name: ${user.name}</h1>

数据库创立 user 表,并灌入数据,运行程序,程序输入后果如下:

至此,Spring Boot + MyBatis + Spring MVC + Freemarker 曾经齐全能失常工作。

Spring Boot 应用 Ehcache 缓存

最初介绍应用 Ehcache 缓存加强程序性能。

首先引入 Ehcache 依赖。在 pom.xml 中引入 ehcache:

...
<dependency>
    <groupId>net.sf.ehcache</groupId>
    <artifactId>ehcache</artifactId>
</dependency>

</dependencies>

而后在 resouces 目录下创立 ehcache.xml 配置文件(Spring Boot 会扫描这个门路,因而请保障文件名正确),并输出以下内容:

<ehcache>

<diskStore path="java.io.tmpdir"/>
<defaultCache
        maxElementsInMemory="10000"
        eternal="false"
        timeToIdleSeconds="120"
        timeToLiveSeconds="120"
        overflowToDisk="false"
        diskPersistent="false"
        diskExpiryThreadIntervalSeconds="120"
/>
<cache name="user"
       maxElementsInMemory="10000"
       eternal="true"
       overflowToDisk="true"
       diskPersistent="true"
       diskExpiryThreadIntervalSeconds="600"/>

</ehcache>

其中:

  1. name: 缓存名称。
  2. maxElementsInMemory:缓存最大个数。
  3. eternal: 对象是否永恒无效,一但设置了,timeout 将不起作用。
  4. timeToIdleSeconds:设置对象在生效前的容许闲置工夫(单位:秒)。仅当 eternal=false 对象不是永恒无效时应用,可选属性,默认值是 0,也就是可闲置工夫无穷大。
  5. timeToLiveSeconds:设置对象在生效前容许存活工夫(单位:秒)。最大工夫介于创立工夫和生效工夫之间。仅当 eternal=false 对象不是永恒无效时应用,默认是 0.,也就是对象存活工夫无穷大。
  6. overflowToDisk:当内存中对象数量达到 maxElementsInMemory 时,Ehcache 将会对象写到磁盘中。
  7. diskSpoolBufferSizeMB:这个参数设置 DiskStore(磁盘缓存)的缓存区大小。默认是 30MB。每个 Cache 都应该有本人的一个缓冲区。
  8. maxElementsOnDisk:硬盘最大缓存个数。
  9. diskPersistent:是否缓存虚拟机重启期数据。
  10. diskExpiryThreadIntervalSeconds:磁盘生效线程运行工夫距离,默认是 120 秒。
  11. memoryStoreEvictionPolicy:当达到 maxElementsInMemory 限度时,Ehcache 将会依据指定的策略去清理内存。默认策略是 LRU(最近起码应用)。你能够设置为 FIFO(先进先出)或是 LFU(较少应用)。
  12. clearOnFlush:内存数量最大时是否革除。
  13. diskStore 则示意长期缓存的硬盘目录。

而后在应用程序中配置开启缓存:

package com.tlanyan.springboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

@SpringBootApplication
@EnableCaching
public class SpringbootApplication {

public static void main(String\[\] args) {SpringApplication.run(SpringbootApplication.class, args);
}

}

以及在 service 层开启缓存:

package com.tlanyan.springboot.service.impl;

import com.tlanyan.springboot.entity.User;
import com.tlanyan.springboot.mapper.UserMapper;
import com.tlanyan.springboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@CacheConfig(cacheNames = “user”)
public class UserServiceImpl implements UserService {

@Autowired
private UserMapper userMapper;

@Override
@Cacheable
public User findById(Integer id) {return userMapper.findById(id);
}

@Override
@Cacheable
public List<User> getAll() {return userMapper.getAll();
}

}

留神,cacheNames的值须要在 ehcache.xml 中存在。

参考

  1. Spring Boot 干货系列:(一)优雅的入门篇
  2. SpringBoot+MySQL+MyBatis 的入门教程
  3. Springboot 系列(四)web 动态资源配置
  4. Spring Boot 缓存利用 Ehcache 入门教程
  5. Spring Boot2 系列教程(三十)Spring Boot 整合 Ehcache
正文完
 0