wix-embedded-mysql,maven使用嵌入式MySQL记录

5 篇文章 0 订阅
3 篇文章 0 订阅

Embedded MySql库提供了一种在集成测试中运行真实MySql的方法。我们可以通过集成该jar包,实现内嵌式MySQL,不需要安装Mysql,即可进行数据库增删改查等相关操作

github: https://github.com/wix/wix-embedded-mysql
社区版mysql手动下载:https://downloads.mysql.com/archives/community/

参考

免安装,还原生产环境,运行中切换版本,这不是我认识的MySQL
EmbeddedMySql的使用

ps:百度搜索的内容好像都只是复制的内容,不知道他们有没有运行测试,我看了下有点蒙圈

实例

参考官方代码,如下:

package com.wix.mysql;

import com.wix.mysql.config.DownloadConfig;
import com.wix.mysql.config.MysqldConfig;
import com.wix.mysql.config.RuntimeConfigBuilder;
import com.wix.mysql.distribution.Version;
import de.flapdoodle.embed.process.config.IRuntimeConfig;

import static com.wix.mysql.config.DownloadConfig.aDownloadConfig;

public class MysqlDownloadAndExtract {

    public static void main(String[] args) {
        DownloadConfig downloadConfig = aDownloadConfig().withCacheDir(args[0]).build();
        MysqldConfig mysqldConfig = MysqldConfig.aMysqldConfig(Version.valueOf(version(args))).build();
        IRuntimeConfig runtimeConfig = new RuntimeConfigBuilder().defaults(mysqldConfig, downloadConfig).build();
        MysqldStarter mysqldStarter = new MysqldStarter(runtimeConfig);
        mysqldStarter.prepare(mysqldConfig);
    }

    private static String version(final String[] args) {
        final String majorVersion = args[1];
        final String minorVersion = args.length > 2 ? args[2] : "latest";
        return "v" + majorVersion.replace('.', '_') + "_" + minorVersion;
    }
}

上面的代码应该是通过jar运行,进行下载的操作

本地运行

引入jar包

<dependency>
    <groupId>com.wix</groupId>
    <artifactId>wix-embedded-mysql</artifactId>
    <version>[4.5.0,)</version>
</dependency>

直接复制代码到本地报错
在这里插入图片描述MysqldStarter的源码是这样的,不是public。━┳━ ━┳━

package com.wix.mysql;

import com.wix.mysql.config.MysqldConfig;
import de.flapdoodle.embed.process.config.IRuntimeConfig;
import de.flapdoodle.embed.process.distribution.Distribution;
import de.flapdoodle.embed.process.extract.IExtractedFileSet;
import de.flapdoodle.embed.process.runtime.Starter;

class MysqldStarter extends Starter<MysqldConfig, MysqldExecutable, MysqldProcess> {

    public MysqldStarter(final IRuntimeConfig config) {
        super(config);
    }

    @Override
    protected MysqldExecutable newExecutable(
            final MysqldConfig config,
            final Distribution distribution,
            final IRuntimeConfig runtime,
            final IExtractedFileSet exe) {
        return new MysqldExecutable(distribution, config, runtime, exe);
    }
}

那就本地实现,反正代码不多。结果还报错
在这里插入图片描述继续提取。。。提供类型不一致(@_@😉
在这里插入图片描述再加把劲。。。好了,总共提取的内容如下:
在这里插入图片描述
源代码位置是:
在这里插入图片描述

提取的代码

MysqldStarter
import com.wix.mysql.config.MysqldConfig;
import de.flapdoodle.embed.process.config.IRuntimeConfig;
import de.flapdoodle.embed.process.distribution.Distribution;
import de.flapdoodle.embed.process.extract.IExtractedFileSet;
import de.flapdoodle.embed.process.runtime.Starter;
/**
 * MysqldStarter类说明:
 *
 * @author z.y.l
 * @version v1.0
 * @date 2020-09-15
 */
class MysqldStarter extends Starter<MysqldConfig, MysqldExecutable, MysqldProcess> {
    public MysqldStarter(final IRuntimeConfig config) {
        super(config);
    }
    @Override
    protected MysqldExecutable newExecutable(
            final MysqldConfig config,
            final Distribution distribution,
            final IRuntimeConfig runtime,
            final IExtractedFileSet exe) {
        return new MysqldExecutable(distribution, config, runtime, exe);
    }
}
MysqldExecutable
import com.wix.mysql.config.MysqldConfig;
import com.wix.mysql.distribution.Setup;
import de.flapdoodle.embed.process.config.IRuntimeConfig;
import de.flapdoodle.embed.process.distribution.Distribution;
import de.flapdoodle.embed.process.extract.IExtractedFileSet;
import de.flapdoodle.embed.process.runtime.Executable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
/**
 * MysqldExecutable类说明:
 *
 * @author z.y.l
 * @version v1.0
 * @date 2020-09-15
 */
class MysqldExecutable  extends Executable<MysqldConfig, MysqldProcess> {
    private final static Logger logger = LoggerFactory.getLogger(MysqldExecutable.class);
    private final IExtractedFileSet executable;
    MysqldExecutable(
            final Distribution distribution,
            final MysqldConfig config,
            final IRuntimeConfig runtimeConfig,
            final IExtractedFileSet executable) {
        super(distribution, config, runtimeConfig, executable);
        this.executable = executable;
    }
    @Override
    protected MysqldProcess start(
            final Distribution distribution,
            final MysqldConfig config,
            final IRuntimeConfig runtime) throws IOException {
        logger.info("Preparing mysqld for startup");
        Setup.apply(config, executable, runtime);
        logger.info("Starting MysqldProcess");
        return new MysqldProcess(distribution, config, runtime, this);
    }
    File getBaseDir() {
        return executable.baseDir();
    }
}
MysqldProcess
import com.wix.mysql.config.MysqldConfig;
import com.wix.mysql.distribution.Service;
import com.wix.mysql.io.NotifyingStreamProcessor;
import de.flapdoodle.embed.process.config.IRuntimeConfig;
import de.flapdoodle.embed.process.distribution.Distribution;
import de.flapdoodle.embed.process.distribution.Platform;
import de.flapdoodle.embed.process.extract.IExtractedFileSet;
import de.flapdoodle.embed.process.io.Processors;
import de.flapdoodle.embed.process.io.StreamToLineProcessor;
import de.flapdoodle.embed.process.runtime.AbstractProcess;
import de.flapdoodle.embed.process.runtime.ProcessControl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.lang.reflect.Field;
import java.nio.file.Paths;
import java.util.List;

import static com.wix.mysql.utils.Utils.closeCloseables;
import static com.wix.mysql.utils.Utils.readToString;
import static de.flapdoodle.embed.process.distribution.Platform.Windows;
import static java.lang.String.format;
import static java.util.concurrent.TimeUnit.MILLISECONDS;

/**
 * MysqldProcess类说明:
 *
 * @author z.y.l
 * @version v1.0
 * @date 2020-09-15
 */
class MysqldProcess extends AbstractProcess<MysqldConfig, MysqldExecutable, MysqldProcess> {
    private final static Logger logger = LoggerFactory.getLogger(MysqldProcess.class);

    private NotifyingStreamProcessor outputWatch;

    public MysqldProcess(
            final Distribution distribution,
            final MysqldConfig config,
            final IRuntimeConfig runtimeConfig,
            final MysqldExecutable executable) throws IOException {
        super(distribution, config, runtimeConfig, executable);
    }

    @Override
    public void onAfterProcessStart(final ProcessControl process, final IRuntimeConfig runtimeConfig) throws IOException {
        outputWatch = new NotifyingStreamProcessor(StreamToLineProcessor.wrap(runtimeConfig.getProcessOutput().getOutput()));
        Processors.connect(process.getReader(), outputWatch);
        Processors.connect(process.getError(), outputWatch);
        NotifyingStreamProcessor.ResultMatchingListener startupListener = outputWatch.addListener(new NotifyingStreamProcessor.ResultMatchingListener("ready for connections"));

        try {
            startupListener.waitForResult(getConfig().getTimeout(MILLISECONDS));

            if (!startupListener.isInitWithSuccess()) {
                throw new RuntimeException("mysql start failed with error: " + startupListener.getFailureFound());
            }
        } catch (Exception e) {
            // emit IO exception for {@link AbstractProcess} would try to stop running process gracefully
            throw new IOException(e);
        }
    }

    @Override
    protected List<String> getCommandLine(Distribution distribution, MysqldConfig config, IExtractedFileSet exe) throws IOException {
        return Service.commandLine(config, exe);
    }

    @Override
    protected synchronized void stopInternal() {
        logger.info("try to stop mysqld");
        if (!stopUsingMysqldadmin()) {
            logger.warn("could not stop mysqld via mysqladmin, try next");
            if (!sendKillToProcess()) {
                logger.warn("could not stop mysqld, try next");
                if (!sendTermToProcess()) {
                    logger.warn("could not stop mysqld, try next");
                    if (!tryKillToProcess()) {
                        logger.warn("could not stop mysqld the second time, try one last thing");
                        try {
                            stopProcess();
                        } catch (IllegalStateException e) {
                            logger.error("error while trying to stop mysql process", e);
                        }
                    }
                }
            }

        }
    }

    @Override
    protected void cleanupInternal() {
    }

    private boolean stopUsingMysqldadmin() {
        NotifyingStreamProcessor.ResultMatchingListener shutdownListener = outputWatch.addListener(new NotifyingStreamProcessor.ResultMatchingListener(": Shutdown complete"));
        boolean retValue = false;
        Reader stdErr = null;

        try {
            String cmd = Paths.get(getExecutable().getFile().baseDir().getAbsolutePath(), "bin", "mysqladmin").toString();

            Process p = Runtime.getRuntime().exec(new String[]{
                    cmd, "--no-defaults", "--protocol=tcp",
                    format("-u%s", MysqldConfig.SystemDefaults.USERNAME),
                    format("--port=%s", getConfig().getPort()),
                    "shutdown"});
            //TODO: make wait with timeout
            retValue = p.waitFor() == 0;
            stdErr = new InputStreamReader(p.getErrorStream());
            if (retValue) {
                shutdownListener.waitForResult(getConfig().getTimeout(MILLISECONDS));
                //TODO: figure out a better strategy for this. It seems windows does not actually shuts down process after it says it does.
                if (Platform.detect() == Windows) {
                    Thread.sleep(2000);
                }
                if (!shutdownListener.isInitWithSuccess()) {
                    logger.error("mysql shutdown failed. Expected to find in output: 'Shutdown complete', got: " + shutdownListener.getFailureFound());
                    retValue = false;
                } else {
                    logger.debug("mysql shutdown succeeded.");
                    retValue = true;
                }
            } else {
                String errOutput = readToString(stdErr);
                if (errOutput.contains("Can't connect to MySQL server on")) {
                    logger.warn("mysql was already shutdown - no need to add extra shutdown hook - process does it out of the box.");
                    retValue = true;
                } else {
                    logger.error("mysql shutdown failed with error code: " + p.waitFor() + " and message: " + errOutput);
                }
            }
        } catch (InterruptedException | IOException e) {
            logger.warn("Encountered error why shutting down process.", e);
        } finally {
            closeCloseables(stdErr);
        }

        return retValue;
    }

    /**
     * Work-around to get Executable in hooks where it's not provided and as
     * all init is done in base class constructor, local vars are still not
     * initialized:/
     */
    private MysqldExecutable getExecutable() {
        try {
            Field f = AbstractProcess.class.getDeclaredField("executable");
            f.setAccessible(true);
            return (MysqldExecutable) f.get(this);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

测试代码

在这里插入图片描述居然不支持,只能看源码怎么验证了。(~ ̄(OO) ̄)ブ

public enum Version implements IVersion {
    v5_5_40("5.5", 40, MacOsVersion.v10_6, TGZ, Platform.Linux, Platform.OS_X),
    v5_5_50("5.5", 50, MacOsVersion.v10_9, TGZ, Platform.Linux, Platform.OS_X),
    v5_5_51("5.5", 51, MacOsVersion.v10_9, TGZ, Platform.Linux, Platform.OS_X),
    v5_5_52("5.5", 52, MacOsVersion.v10_9, TGZ, Platform.Linux, Platform.OS_X),
    v5_5_latest(v5_5_52),
    v5_6_21("5.6", 21, MacOsVersion.v10_9),
    v5_6_22("5.6", 22, MacOsVersion.v10_9),
    v5_6_23("5.6", 23, MacOsVersion.v10_9),
    v5_6_24("5.6", 24, MacOsVersion.v10_9),
    v5_6_31("5.6", 31, MacOsVersion.v10_11),
    v5_6_32("5.6", 32, MacOsVersion.v10_11),
    v5_6_33("5.6", 33, MacOsVersion.v10_11),
    v5_6_34("5.6", 34, MacOsVersion.v10_11),
    v5_6_35("5.6", 35, MacOsVersion.v10_12),
    v5_6_36("5.6", 36, MacOsVersion.v10_12),
    v5_6_latest(v5_6_36),
    v5_7_10("5.7", 10, MacOsVersion.v10_10),
    v5_7_13("5.7", 13, MacOsVersion.v10_11),
    v5_7_14("5.7", 14, MacOsVersion.v10_11),
    v5_7_15("5.7", 15, MacOsVersion.v10_11),
    v5_7_16("5.7", 16, MacOsVersion.v10_11),
    v5_7_17("5.7", 17, MacOsVersion.v10_12),
    v5_7_18("5.7", 18, MacOsVersion.v10_12),
    v5_7_19("5.7", 19, MacOsVersion.v10_12),
    v5_7_27("5.7", 27, MacOsVersion.v10_14),
    v5_7_latest(v5_7_27),
    v8_0_11("8.0", 11, MacOsVersion.v10_13),
    v8_0_17("8.0", 17, MacOsVersion.v10_14, TXZ, Platform.Linux, Platform.Windows, Platform.OS_X),
    v8_latest(v8_0_17);

    private enum MacOsVersion {
        v10_6("osx"),
        v10_9("osx"),
        v10_10("osx"),
        v10_11("osx"),
        v10_12("macos"),
        v10_13("macos"),
        v10_14("macos");
...
}
public enum Platform {
	Linux,
	Windows,
	OS_X,
	Solaris,
	FreeBSD;
}

看到原来支持的版本是5.5.40-8.0.17,支持的平台linux\windows\os_x\solaris\freebsd,只有5.6.21-8.latest支持window

下载window支持的版本

    public static void main(String[] args) {
        String[] strings = {"D:\\_data\\mysqlEmbedded8.0","8","latest"};
        System.out.println(version(strings));
        down(strings);
    }
    public static void down(String[] args) {
        DownloadConfig downloadConfig = aDownloadConfig().withCacheDir(args[0]).build();
        MysqldConfig mysqldConfig = MysqldConfig.aMysqldConfig(Version.valueOf(version(args))).build();
        IRuntimeConfig runtimeConfig = new RuntimeConfigBuilder().defaults(mysqldConfig, downloadConfig).build();
        MysqldStarter mysqldStarter = new MysqldStarter(runtimeConfig);
        mysqldStarter.prepare(mysqldConfig);
    }

    private static String version(final String[] args) {
        final String majorVersion = args[1];
        final String minorVersion = args.length > 2 ? args[2] : "latest";
        return "v" + majorVersion.replace('.', '_') + "_" + minorVersion;
    }

控制台输出

v8_latest
Download Version 8.0.17:Windows:B64 START
Download Version 8.0.17:Windows:B64 DownloadSize: 266548342
Download Version 8.0.17:Windows:B64 0%
Download Version 8.0.17:Windows:B64 5%
Download Version 8.0.17:Windows:B64 10%
Download Version 8.0.17:Windows:B64 15%
Download Version 8.0.17:Windows:B64 20%
Download Version 8.0.17:Windows:B64 25%
Download Version 8.0.17:Windows:B64 30%
Download Version 8.0.17:Windows:B64 35%
Download Version 8.0.17:Windows:B64 40%
Download Version 8.0.17:Windows:B64 45%
Download Version 8.0.17:Windows:B64 50%
Download Version 8.0.17:Windows:B64 55%
Download Version 8.0.17:Windows:B64 60%
Download Version 8.0.17:Windows:B64 65%
Download Version 8.0.17:Windows:B64 70%
Download Version 8.0.17:Windows:B64 75%
Download Version 8.0.17:Windows:B64 80%
Download Version 8.0.17:Windows:B64 85%
Download Version 8.0.17:Windows:B64 90%
Download Version 8.0.17:Windows:B64 95%
Download Version 8.0.17:Windows:B64 100%
Download Version 8.0.17:Windows:B64 downloaded with 1657kb/s
Download Version 8.0.17:Windows:B64 DONE
Extract D:\_data\mysqlEmbedded8.0\MySQL-8.0\mysql-8.0.17-winx64.zip START
Extract D:\_data\mysqlEmbedded8.0\MySQL-8.0\mysql-8.0.17-winx64.zip extract mysql-8.0.17-winx64/bin/mysql.exe
Extract D:\_data\mysqlEmbedded8.0\MySQL-8.0\mysql-8.0.17-winx64.zip extract mysql-8.0.17-winx64/bin/mysqladmin.exe
Extract D:\_data\mysqlEmbedded8.0\MySQL-8.0\mysql-8.0.17-winx64.zip extract mysql-8.0.17-winx64/bin/mysqld.exe
Extract D:\_data\mysqlEmbedded8.0\MySQL-8.0\mysql-8.0.17-winx64.zip extract mysql-8.0.17-winx64/share/english/errmsg.sys
Extract D:\_data\mysqlEmbedded8.0\MySQL-8.0\mysql-8.0.17-winx64.zip nothing left
Extract D:\_data\mysqlEmbedded8.0\MySQL-8.0\mysql-8.0.17-winx64.zip DONE
17:52:40.719 [Thread-0] DEBUG de.flapdoodle.embed.process.io.file.Files - could delete D:\_project\IDEA-2020-1\spring-boot-branch-demo\target\mysql-8.0-870a43c2-52f4-475d-a8e5-3d6ad5735dbf\bin\mysql.exe
17:52:40.722 [Thread-0] DEBUG de.flapdoodle.embed.process.io.file.Files - could delete D:\_project\IDEA-2020-1\spring-boot-branch-demo\target\mysql-8.0-870a43c2-52f4-475d-a8e5-3d6ad5735dbf\bin\mysqladmin.exe
17:52:40.722 [Thread-0] DEBUG de.flapdoodle.embed.process.io.file.Files - could delete D:\_project\IDEA-2020-1\spring-boot-branch-demo\target\mysql-8.0-870a43c2-52f4-475d-a8e5-3d6ad5735dbf\share\english\errmsg.sys
17:52:40.726 [Thread-0] DEBUG de.flapdoodle.embed.process.io.file.Files - could delete D:\_project\IDEA-2020-1\spring-boot-branch-demo\target\mysql-8.0-870a43c2-52f4-475d-a8e5-3d6ad5735dbf\bin\mysqld.exe
17:52:40.730 [Thread-0] DEBUG de.flapdoodle.embed.process.io.file.Files - could delete D:\_project\IDEA-2020-1\spring-boot-branch-demo\target\mysql-8.0-870a43c2-52f4-475d-a8e5-3d6ad5735dbf

进程已结束,退出代码0

对应目录截图,可以看到已下载成功
在这里插入图片描述

测试运行

参考官方代码

package com.wix.mysql;

import com.wix.mysql.config.DownloadConfig;
import com.wix.mysql.config.MysqldConfig;
import com.wix.mysql.config.SchemaConfig;
import org.junit.Ignore;
import org.junit.Test;

import java.util.concurrent.TimeUnit;

import static com.wix.mysql.EmbeddedMysql.anEmbeddedMysql;
import static com.wix.mysql.ScriptResolver.classPathScript;
import static com.wix.mysql.ScriptResolver.classPathScripts;
import static com.wix.mysql.config.Charset.LATIN1;
import static com.wix.mysql.config.Charset.UTF8;
import static com.wix.mysql.config.DownloadConfig.aDownloadConfig;
import static com.wix.mysql.config.MysqldConfig.aMysqldConfig;
import static com.wix.mysql.config.ProxyFactory.aHttpProxy;
import static com.wix.mysql.config.SchemaConfig.aSchemaConfig;
import static com.wix.mysql.distribution.Version.v5_6_latest;
import static com.wix.mysql.distribution.Version.v5_7_latest;

@Ignore
public class JavaUsageExamplesTest {
    @Test
    public void defaultConfigurationAndASingleSchema() {
        EmbeddedMysql mysqld = anEmbeddedMysql(v5_6_latest)
                .addSchema("aschema", classPathScript("db/001_init.sql"))
                .start();
        //do work
        mysqld.stop(); //optional, as there is a shutdown hook
    }
    @Test
    public void defaultConfigurationAndASingleSchemaWithMultipleMigrations() {
        EmbeddedMysql mysqld = anEmbeddedMysql(v5_6_latest)
                .addSchema("aschema", classPathScripts("db/*.sql"))
                .start();
        //do work
        mysqld.stop(); //optional, as there is a shutdown hook
    }
    @Test
    public void mysqldConfigAndMultipleSchemas() {
        MysqldConfig config = aMysqldConfig(v5_7_latest)
                .withCharset(UTF8)
                .withPort(2215)
                .withUser("differentUser", "anotherPasword")
                .build();
        EmbeddedMysql mysqld = anEmbeddedMysql(config)
                .addSchema("aschema", classPathScript("db/001_init.sql"))
                .addSchema("aschema2", classPathScripts("db/*.sql"))
                .start();
        //do work
        mysqld.stop(); //optional, as there is a shutdown hook
    }
    @Test
    public void schemaConfigViaBuilder() {
        SchemaConfig schema = aSchemaConfig("aSchema")
                .withScripts(classPathScript("db/001_init.sql"))
                .withCharset(LATIN1)
                .build();
        EmbeddedMysql mysqld = anEmbeddedMysql(v5_6_latest)
                .addSchema(schema)
                .addSchema("aschema2", classPathScripts("db/*.sql"))
                .start();
        //do work
        mysqld.stop(); //optional, as there is a shutdown hook
    }

    @Test
    public void schemaReset() {
        EmbeddedMysql mysqld = anEmbeddedMysql(v5_6_latest)
                .addSchema("aschema", classPathScript("db/001_init.sql"))
                .start();
        //do work
        SchemaConfig schema = aSchemaConfig("aschema")
                .withScripts(classPathScript("db/001_init.sql"))
                .build();
        mysqld.reloadSchema(schema);
        //continue on doing work
        mysqld.stop(); //optional, as there is a shutdown hook
    }

    @Test
    public void customTimeout() {
        MysqldConfig config = aMysqldConfig(v5_6_latest)
                .withTimeout(2, TimeUnit.MINUTES)
                .build();
        EmbeddedMysql mysqld = anEmbeddedMysql(config)
                .addSchema("aschema", classPathScript("db/001_init.sql"))
                .start();
        //do work
        mysqld.stop(); //optional, as there is a shutdown hook
    }

    @Test
    public void customTempDir() {
        MysqldConfig config = aMysqldConfig(v5_6_latest)
                .withTempDir(System.getProperty("java.io.tmpdir"))
                .build();
        EmbeddedMysql mysqld = anEmbeddedMysql(config)
                .addSchema("aschema", classPathScript("db/001_init.sql"))
                .start();
        //do work
        mysqld.stop(); //optional, as there is a shutdown hook
    }

    @Test
    public void httpProxy() {
        DownloadConfig downloadConfig = aDownloadConfig()
                .withProxy(aHttpProxy("remote.host", 8080))
                .build();
        EmbeddedMysql mysqld = anEmbeddedMysql(v5_6_latest, downloadConfig)
                .addSchema("aschema", classPathScript("db/001_init.sql"))
                .start();
        //do work
        mysqld.stop(); //optional, as there is a shutdown hook
    }
}

本地测试

测试截图
在这里插入图片描述

测试代码


import com.wix.mysql.EmbeddedMysql;
import com.wix.mysql.config.MysqldConfig;
import org.junit.Test;

import static com.wix.mysql.EmbeddedMysql.anEmbeddedMysql;
import static com.wix.mysql.ScriptResolver.classPathScript;
import static com.wix.mysql.distribution.Version.v5_6_latest;

/**
 * JavaUsageExamplesTest类说明:
 *
 * @author z.y.l
 * @version v1.0
 * @date 2020-09-16
 */
public class JavaUsageExamplesTest {
    @Test
    public void defaultConfigurationAndASingleSchema() {
        EmbeddedMysql mysqld = anEmbeddedMysql(v5_6_latest)
                .addSchema("aschema", classPathScript("db/001_init.sql"))
                .start();
        //do work
        MysqldConfig config = mysqld.getConfig();
        System.out.println("嵌入式MySQL信息---start---");
        System.out.println("版本:"+config.getVersion());
        System.out.println("端口:"+config.getPort());
        System.out.println("用户:"+config.getUsername());
        System.out.println("密码:"+config.getPassword());
        System.out.println("编码:"+config.getCharset());
        System.out.println("目录:"+config.getTempDir());
        System.out.println("时区:"+config.getTimeZone());
        System.out.println("嵌入式MySQL信息---end---");
        System.out.println(config);
        mysqld.stop(); //optional, as there is a shutdown hook
    }
}

第一次执行会下载指定版本MySQL,如果不指定路径,就是在C:\Users\用户名\.embedmysql,里面储存的是压缩包
在这里插入图片描述
在这里插入图片描述
运行中,会将压缩包加压到项目的target目录中,执行stop()会自动删除目录

public synchronized void stop() {
	if (!stopped) {
		for (IStopable s : stopables) {
			s.stop();
		}
		stopables = new ArrayList<IStopable>();
		runtimeConfig.getArtifactStore().removeFileSet(distribution, executable);
		stopped = true;
	}
}

测试记录
在这里插入图片描述运行中,可以用数据库管理工具连接。登录方式(root无密码、提供的账户auser密码 sa

在这里插入图片描述在这里插入图片描述连接成功后,可以看到是一个完整的数据库,root账号无限制,无法远程连接
在这里插入图片描述提供的账号是受到权限限制的,可以远程连接
在这里插入图片描述

测试环境支持window的版本

/** 测试数据库5.5初始化 */
@Test
public void initMysql5_5() {
    EmbeddedMysql mysql = anEmbeddedMysql(v5_5_latest).addSchema("zyl", classPathScript("db/001_init.sql")).start();
    mysql.stop();
}
/** 测试数据库5.6初始化 */
@Test
public void initMysql5_6() {
    EmbeddedMysql mysql = anEmbeddedMysql(v5_6_latest).addSchema("zyl", classPathScript("db/001_init.sql")).start();
    mysql.stop();
}
/** 测试数据库5.7初始化 */
@Test
public void initMysql5_7() {
    EmbeddedMysql mysql = anEmbeddedMysql(v5_7_latest).addSchema("zyl", classPathScript("db/001_init.sql")).start();
    mysql.stop();
}
/** 测试数据库8初始化 */
@Test
public void initMysql8() {
    EmbeddedMysql mysql = anEmbeddedMysql(v8_latest).addSchema("zyl", classPathScript("db/001_init.sql")).start();
    mysql.stop();
}

在这里插入图片描述

end

(✿◕‿◕✿)

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值