概述
项目搭建工具及版本:
eclipse / jdk1.8 / springboot2.5.0
1.pom.xml引入相关jar包
<!--mybatis依赖-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
<!--mybatis-plus依赖-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.3.2</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.3.2</version>
</dependency>
<!-- MySQL连接驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- 引入druid支持 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.6</version>
</dependency>
<!--lombok支持简化开发-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
2.application-dev.properties增加配置
#===================== 数据库配置(使用druid)=====================
#mysql
spring.datasource.druid.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.druid.url=jdbc:mysql://你的mysql地址:3306/数据库名称?characterEncoding=utf-8&useSSL=false
spring.datasource.druid.username=root
spring.datasource.druid.password=你的mysql密码
spring.datasource.druid.driver-class-name=com.mysql.cj.jdbc.Driver
#===================== druid连接池配置 =====================
spring.datasource.druid.initial-size=5
spring.datasource.druid.max-active=20
spring.datasource.druid.min-idle=5
spring.datasource.druid.max-wait=60000
spring.datasource.druid.pool-prepared-statements=true
spring.datasource.druid.max-pool-prepared-statement-per-connection-size=20
#spring.datasource.druid.max-open-prepared-statements=
spring.datasource.druid.validation-query=SELECT 1 FROM DUAL
spring.datasource.druid.validation-query-timeout=30000
spring.datasource.druid.test-on-borrow=false
spring.datasource.druid.test-on-return=false
spring.datasource.druid.test-while-idle=true
spring.datasource.druid.time-between-eviction-runs-millis=60000
spring.datasource.druid.min-evictable-idle-time-millis=300000
#spring.datasource.druid.max-evictable-idle-time-millis=
spring.datasource.druid.filters=stat,wall,slf4j
#WebStatFilter配置
spring.datasource.druid.web-stat-filter.enabled=true
spring.datasource.druid.web-stat-filter.url-pattern=/*
spring.datasource.druid.web-stat-filter.exclusions=*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico, /druid/*
spring.datasource.druid.web-stat-filter.session-stat-enable=true
spring.datasource.druid.web-stat-filter.session-stat-max-count=2000
spring.datasource.druid.web-stat-filter.principal-session-name=USER_SESSION
spring.datasource.druid.web-stat-filter.principal-cookie-name=USER_COOKIE
spring.datasource.druid.web-stat-filter.profile-enable=true
#StatViewServlet配置
spring.datasource.druid.stat-view-servlet.enabled=true
spring.datasource.druid.stat-view-servlet.url-pattern=/druid/*
spring.datasource.druid.stat-view-servlet.reset-enable=false
spring.datasource.druid.stat-view-servlet.login-username=
spring.datasource.druid.stat-view-servlet.login-password=
spring.datasource.druid.stat-view-servlet.allow=
spring.datasource.druid.stat-view-servlet.deny=
#Spring监控配置
#Spring监控AOP切入点,如x.y.z.service.*,配置多个英文逗号分隔
spring.datasource.druid.aop-patterns=com.*.*.dao.*,com.*.*.service.*
#如果spring.datasource.druid.aop-patterns要代理的类没有定义interface请设置spring.aop.proxy-target-class=true
#===================== mybatis-plus配置 =====================
#如果是放在src/main/java目录下 classpath:/com/yourpackage/*/mapper/*Mapper.xml
#如果是放在resource目录 classpath:/mapper/*Mapper.xml
mybatis-plus.mapper-locations=classpath:/mapper/*Mapper.xml
#别名包扫描,多个package用逗号或者分号分隔
mybatis-plus.type-aliases-package=com.*.*.dao
#配置返回数据库(column下划线命名&&返回java实体是驼峰命名),自动匹配无需as(没开启这个,SQL需要写as: select user_id as userId)
mybatis-plus.configuration.map-underscore-to-camel-case=true
mybatis-plus.configuration.cache-enabled=false
#配置JdbcTypeForNull, oracle数据库必须配置
mybatis-plus.configuration.jdbc-type-for-null='null'
#开启sql日志
#mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
#主键类型
0:"数据库ID自增", 1:"用户输入ID",2:"全局唯一ID (数字类型唯一ID)", 3:"全局唯一ID UUID";
mybatis-plus.global-config.id-type=0
#字段策略 0:"忽略判断",1:"非 NULL 判断"),2:"非空判断"
mybatis-plus.global-config.field-strategy=2
#驼峰下划线转换
mybatis-plus.global-config.db-column-underline=true
#mp2.3+ 全局表前缀 t_
mybatis-plus.global-config.table-prefix=ht_
#刷新mapper 调试神器
mybatis-plus.global-config.refresh-mapper=true
#数据库大写下划线转换
mybatis-plus.global-config.capital-mode=true
#逻辑删除配置(下面3个配置)
mybatis-plus.global-config.logic-delete-value=4
mybatis-plus.global-config.logic-not-delete-value=0
3.springboot自带logback日志框架,所以只需要启用配置即可。
使用:在需要使用日志的类名位置加入@Slf4j注解即可使用,后面的例子会穿插使用。
配置:logback.xml为自定义日志配置,一般没啥特殊要求模板使用即可,附上本项目的日志配置文件。
配置文件与properties文件同目录/src/main/resources/即可。
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<!-- 修改日志文件名及路径 -->
<property name="logName" value="bbnet-api"/>
<property name="logPath" value="logs"/>
<include resource="org/springframework/boot/logging/logback/defaults.xml" />
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>${CONSOLE_LOG_PATTERN}</pattern>
<charset>utf8</charset>
</encoder>
</appender>
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${logPath}/${logName}.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 保存历史记录到这个文件夹,日起为后缀 -->
<fileNamePattern>${logPath}/${logName}.%d{yyyy-MM-dd}.log</fileNamePattern>
<!-- 自动保存30天之内的日志文件 -->
<maxHistory>30</maxHistory>
</rollingPolicy>
<encoder>
<pattern>${CONSOLE_LOG_PATTERN}</pattern>
<charset>utf8</charset>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="CONSOLE"></appender-ref>
<appender-ref ref="FILE"></appender-ref>
</root>
<!-- mybatis打印sql配置,可以指定到类,如果开启了sql插件这里就不用单独配置 -->
<!-- <logger name="com.*.*.mapper" level="TRACE" additivity="true" /> -->
<!-- 排除不需要打印的日志 -->
<logger name="com.alibaba.druid.pool.DruidDataSource" level="OFF" />
<logger name="org.springframework.web.servlet.DispatcherServlet" level="OFF" />
<logger name="org.apache.catalina.core.ContainerBase" level="OFF" />
</configuration>
4.增加druid数据源和数据监控配置类
有这3个功能类即可。
package com.bbnet.config.druid;
import javax.sql.DataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.alibaba.druid.pool.DruidDataSource;
import lombok.extern.slf4j.Slf4j;
/**
* druid注册到容器
*
*
* @author sgc
* @since 2021-08-25
*/
@Configuration
@Slf4j
public class DruidConfig {
// protected final Logger log = LoggerFactory.getLogger(DruidConfig.class);
@ConfigurationProperties(prefix = "spring.datasource.druid")
@Bean
public DataSource druid(){
log.info("Druid数据源和监控配置初始化完成");
return new DruidDataSource();
}
}
package com.bbnet.config.druid;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import com.alibaba.druid.support.http.WebStatFilter;
/**
* @Description druid过滤器
* <pre>
*
* </pre>
*
*
* @author sgc
* @date 2021-08-25
*/
@WebFilter(filterName="druidWebStatFilter",
urlPatterns="/*",
initParams={
@WebInitParam(name="exclusions",value="*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*")//忽略资源
}
)
public class DruidStatFilter extends WebStatFilter {
}
package com.bbnet.config.druid;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import com.alibaba.druid.support.http.StatViewServlet;
/**
* 配置druid的servlet,druid数据源状态监控
*
* @author sgc
* @date 2021-08-25
*/
@WebServlet(urlPatterns="/druid/*",
initParams={
@WebInitParam(name="allow",value=""),// IP白名单(没有配置或者为空,则允许所有访问)
@WebInitParam(name="deny",value=""),// IP黑名单 (存在共同时,deny优先于allow)
@WebInitParam(name="loginUsername",value=""),// 用户名
@WebInitParam(name="loginPassword",value=""),// 密码
@WebInitParam(name="resetEnable",value="true")// 禁用HTML页面上的“Reset All”功能
}
)
public class DruidStatViewServlet extends StatViewServlet {
private static final long serialVersionUID = 1L;
}
以上配置完成项目启动则通过localhost:8888/druid/即可访问druid的监控系统。
druid相关问题这里不做赘述。
5.项目启动类加上注解@ServletComponentScan
package com.bbnet;
import java.net.InetAddress;
import java.net.UnknownHostException;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.Environment;
/**
* @Description 项目启动类
* <pre>
*
* </pre>
*
*
* @author sgc
* @date 2021-08-25
*/
@SpringBootApplication
@ServletComponentScan
public class BbnetApplication {
public static void main(String[] args) throws UnknownHostException {
//
SpringApplication.run(BbnetApplication.class);
//System.setProperty("spring.devtools.restart.enabled", "true");
ConfigurableApplicationContext application = SpringApplication.run(BbnetApplication.class, args);
Environment env = application.getEnvironment();
String ip = InetAddress.getLocalHost().getHostAddress();
String port = env.getProperty("server.port");
String path = env.getProperty("server.servlet.context-path");
System.out.println(
"n--------后台服务启动成功--------------------------------------------------------------nt" +
"本地访问地址: tthttp://localhost:" + port + path + "/nt" +
"公网访问地址: tthttp://" + ip + ":" + port + path + "/nt" +
"Swagger接口文档地址: thttp://" + ip + ":" + port + path + "/swagger-ui.htmlnt" +
"Druid数据监控地址: thttp://" + ip + ":" + port + path + "/druid/n" +
"-----------------------------------------------------------------------------------");
}
}
6.增加mybatis-plus配置类
package com.bbnet.config.mybatisplus;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import lombok.extern.slf4j.Slf4j;
/**
* mybatis-plus配置
*
*
* @author sgc
* @since 2021-08-25
*/
@EnableTransactionManagement
@Configuration
@MapperScan(basePackages = "com.**.mapper")
@Slf4j
public class MybatisPlusConfig {
// protected final Logger log = LoggerFactory.getLogger(MybatisPlusConfig.class);
@Bean
public PaginationInterceptor paginationInterceptor() {
PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
// 设置请求的页面大于最大页后操作, true调回到首页,false 继续请求
默认false
// paginationInterceptor.setOverflow(false);
// 设置最大单页限制数量,默认 500 条,-1 不受限制
// paginationInterceptor.setLimit(500);
log.info("Mybatis-Plus配置初始化完成");
return paginationInterceptor;
}
}
PS:因为本示例将来会读取/src/main/resources/下mapper文件夹下的xml文件,所以保证/src/main/resources/下已经新建该目录。
7.mysql示例表结构
DROP TABLE IF EXISTS `ht_area`;
CREATE TABLE `ht_area` (
`id` int(11) NOT NULL COMMENT '主键',
`name` varchar(64) NOT NULL COMMENT '名称',
`parent_id` int(11) DEFAULT NULL COMMENT '父区域ID',
`type` int(11) NOT NULL COMMENT '区域类型,1:省份;2:城市;3:区县',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='区域信息表';
SET FOREIGN_KEY_CHECKS = 1;
8.创建mybatis-plus增强controller类,将来所有的业务controller类将继承该类。
package com.bbnet.common.base;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
/**
* 所有控制器的父类
*
* @param <T>
*
* @author sgc
* @since 2021-08-25
*/
public abstract class BaseController<T> {
public abstract IService<T> getIService();
protected final Logger log = LoggerFactory.getLogger(BaseController.class);
/**
* 查询所有
* @return
*/
@PostMapping("/list")
@ApiOperation(value="查询所有", notes="")
public List<T> list() {
return getIService().list();
}
/**
* 分页查询
* @param current
* @param size
* @return
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
@PostMapping("/page")
@ApiOperation(value="分页查询", notes="比如:当前第1页查询10条数据,则current=1,size=10")
@ApiImplicitParams({
@ApiImplicitParam(name = "current", value = "当前第几页", required = true, dataType = "String"),
@ApiImplicitParam(name = "size", value = "查询几条", required = true, dataType = "String")
})
public IPage<T> page(@RequestParam String current, @RequestParam String size) {
Page<T> page = new Page(Long.parseLong(current), Long.parseLong(size));
return getIService().page(page);
}
/**
* 新增
* @param t
* @return
*/
@PostMapping("/add")
@ApiOperation(value="新增", notes="")
public String add(@RequestBody T t) {
return getIService().save(t) ? "添加成功!" : "添加失败!";
}
/**
* 更新
* @param t
* @return
*/
@PostMapping("/update")
@ApiOperation(value="更新", notes="")
public String update(@RequestBody T t) {
return getIService().updateById(t) ? "修改成功!" : "修改失败!";
}
/**
* 删除
* @param id
* @return
*/
@PostMapping("/deleteById")
@ApiOperation(value="删除", notes="")
@ApiImplicitParams({
@ApiImplicitParam(name = "id", value = "主键id", required = true, dataType = "String")
})
public String deleteById(@RequestParam String id) {
return getIService().removeById(id) ? "删除成功!" : "删除失败!";
}
}
9.创建vo/mapper/service/impl/controller的demo示例代码
package com.bbnet.demo.vo;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.experimental.Accessors;
@Data
@Accessors(chain = true)
@TableName("ht_area")
public class Area {
@TableId
private Integer id;
private String name;
private Integer parentId;
private Integer type;
}
package com.bbnet.demo.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.bbnet.demo.vo.Area;
public interface AreaService extends IService<Area> {
String say();
}
package com.bbnet.demo.service.impl;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bbnet.demo.mapper.AreaMapper;
import com.bbnet.demo.service.AreaService;
import com.bbnet.demo.vo.Area;
@Service
public class AreaServiceImpl extends ServiceImpl<AreaMapper, Area> implements AreaService {
@Override
public String say() {
}
}
package com.bbnet.demo.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.baomidou.mybatisplus.extension.service.IService;
import com.bbnet.common.base.BaseController;
import com.bbnet.demo.service.AreaService;
import com.bbnet.demo.vo.Area;
@RestController
@RequestMapping("/demo")
public class DemoController extends BaseController<Area> {
private static final Logger log = LoggerFactory.getLogger(DemoController.class);
@Autowired
private AreaService areaService;
@Override
public IService<Area> getIService() {
return areaService;
}
@PostMapping("/catchReq")
public String catchReq(@RequestParam String id) {
log.info("初始化了getIService...");
return areaService.say();
}
}
10.测试controller的继承类
因为DemoController继承了BaseController类,所以BaseController中的方法是可以提供给demo去使用的,故直接请求localhost:8888/bbnet/demo/list是可以查到数据库的数据的
11.测试druid的监控页面
请求http://127.0.0.1:8888/bbnet/druid/地址,如下图:
至此,框架集成日志、mysql、mybatis、druid、mybatis-plus完成,代码细节上可能有一点未注解清楚的地方,有问题请留言。
最后
以上就是专一小鸽子为你收集整理的搭建springboot后端框架(二)集成druid数据源+druid监控+mybatis-plus+mysql+logback日志的全部内容,希望文章能够帮你解决搭建springboot后端框架(二)集成druid数据源+druid监控+mybatis-plus+mysql+logback日志所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复