springboot整合内置嵌入式mysql服务教程
Posted 洛阳泰山
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了springboot整合内置嵌入式mysql服务教程相关的知识,希望对你有一定的参考价值。
pom文件引入依赖
<!-- 内嵌mysql server -->
<dependency>
<groupId>com.wix</groupId>
<artifactId>wix-embedded-mysql</artifactId>
<version>4.6.1</version>
<scope>compile</scope>
</dependency>
springboot项目整合EmbeddedMysql配置类
import com.wix.mysql.EmbeddedMysql;
import com.wix.mysql.ScriptResolver;
import com.wix.mysql.config.MysqldConfig;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.concurrent.TimeUnit;
import static com.wix.mysql.EmbeddedMysql.anEmbeddedMysql;
import static com.wix.mysql.config.Charset.UTF8;
import static com.wix.mysql.config.MysqldConfig.aMysqldConfig;
import static com.wix.mysql.distribution.Version.v5_6_23;
@Configuration
@ConditionalOnProperty(prefix = "cms",name = "embedded.mysql.enabled",havingValue = "true")
public class EmbeddedMysqlConfig {
private EmbeddedMysql mysql;
@PostConstruct
public void launchDb(){
//mysql版本
MysqldConfig config = aMysqldConfig(v5_6_23)
.withCharset(UTF8)
//端口号
.withPort(3306)
//用户名密码
.withUser("tarzan", "123456")
//时区
.withTimeZone("Asia/Shanghai")
//超时
.withTimeout(1, TimeUnit.MINUTES)
.withServerVariable("max_connect_errors", 666)
.withTempDir("C:\\\\Users\\\\liuya\\\\Desktop\\\\data\\\\")
.build();
mysql = anEmbeddedMysql(config)
//初始化数据表结构
.addSchema("tarzan_cms", ScriptResolver.classPathScript("db/schema.sql"))
.start();
System.out.println(mysql.getConfig().toString());
}
@PreDestroy
public void stopDb(){
mysql.stop();
}
}
配置完,springboot项目启动时候,会先启动内置的mysql服务,spring配置文件配置数据库连接
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driverClassName: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/tarzan_cms?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true
username: tarzan
password: 123456
这样就省去了,安装mysql的步骤,不过目前这种配置方式,每次项目重启,会新建一个新的mysql服务,原来的数据会丢失。
详细大家可以参考EmbeddedMysql的GitHub源码。
GitHub - wix/wix-embedded-mysql: embedded mysql based on https://github.com/flapdoodle-oss/de.flapdoodle.embed.process
以上是关于springboot整合内置嵌入式mysql服务教程的主要内容,如果未能解决你的问题,请参考以下文章
Springboot如何整合RabbitMq,若不会,我便手把手教你超级详细