上一节我们学习了spring boot整合nacos,知道了nacos具有动态的服务注册、配置管理和服务发现的作用,现在我以数据库的配置为例来演示一下nacos是如何进行数据的的配置管理的。
创建数据库
创建两个数据库一个为mybatis-plus, 一个为test2
建表语句
CREATE TABLE test2.`user` ( `id` bigint(20) NOT NULL COMMENT '主键ID', `user_name` varchar(30) DEFAULT NULL COMMENT '姓名', `user_age` int(11) DEFAULT NULL COMMENT '年龄', `user_email` varchar(50) DEFAULT NULL COMMENT '邮箱', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
加入依赖
<!--mysql连接器-->
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <!-- mybatis-plus--> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.0.5</version> </dependency>
在学习过程中我很好奇mysql-connector-java和mybatis-plus-boot-starter有什么区别?它们各自的作用是什么?
mysql-connector-java
what? 是mysql的一个客户端,相当于命令行客户端和图形化界面一样。
how? 用于连接数据库、发送sql语句、处理结果集
可参考https://blog.csdn.net/keyboard_/article/details/114337739 这位博主讲得很形象。
mybatis-plus-boot-starter
what? 是基于java的持久化框架
how? 自动装配数据源、提供基本的JDBCTemplate简化数据库的操作、事务控制支持
mybatis-plus-boot-start会引入HiKariCp数据库连接池,自动配置dataSource、transationManager、jdbcTemplate
mysql-connector-java和mybatis-plus-boot-starter的区别
mysql-connector-java是真正操作mysql数据库的客户端,mybatis-plus-boot-starter对JDBCTemplate底层还是调用mysql-connector-java的方法操作数据库
可参考:https://www.cnblogs.com/liyanbofly/p/16515856.html 这位博主讲得也很好
pom.xml
此处我是使用nacos进行服务注册、发现以及配置管理,可参考上一篇文章,spring boot整合nacos
<?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.example</groupId> <artifactId>nacos-demo</artifactId> <version>1.0-SNAPSHOT</version> </parent> <artifactId>nacos-provider</artifactId> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.24</version> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!--nacos注册中心--> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> </dependency> <!--Nacos配置中心--> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId> </dependency> <!mysql连接器> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <!-- mybatis plus --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.0.5</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
代码生成
生成mapper、service、model对象
分页插件 GeneratorCodeConfig
package com.example.nacosprovider.generator; import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.stereotype.Controller; @Configuration public class MybatisPlusConfig { /** * 分页插件 */ @Bean public PaginationInterceptor paginationInterceptor() { return new PaginationInterceptor(); } }
代码生成 MybatisPlusConfig
package com.example.nacosprovider.generator; import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException; import com.baomidou.mybatisplus.generator.AutoGenerator; import com.baomidou.mybatisplus.generator.config.*; import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy; import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine; import org.apache.commons.lang3.StringUtils; import java.util.Scanner; public class GeneratorCodeConfig { public static String scanner(String tip) { Scanner scanner = new Scanner(System.in); StringBuilder help = new StringBuilder(); help.append("请输入" + tip + ":"); System.out.println(help.toString()); if (scanner.hasNext()) { String ipt = scanner.next(); if (StringUtils.isNotEmpty(ipt)) { return ipt; } } throw new MybatisPlusException("请输入正确的" + tip + "!"); } public static void main(String[] args) { // 代码生成器 AutoGenerator mpg = new AutoGenerator(); // 全局配置 GlobalConfig gc = new GlobalConfig(); String projectPath = System.getProperty("user.dir"); gc.setOutputDir(projectPath + "/nacos-provider/src/main/java"); gc.setAuthor("astupidcoder"); gc.setOpen(false); //实体属性 Swagger2 注解 gc.setSwagger2(false); mpg.setGlobalConfig(gc); // 数据源配置 DataSourceConfig dsc = new DataSourceConfig(); dsc.setUrl("jdbc:mysql://127.0.0.1:3306/test2?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=true"); dsc.setDriverName("com.mysql.cj.jdbc.Driver"); dsc.setUsername("root"); dsc.setPassword("123456"); mpg.setDataSource(dsc); // 包配置 PackageConfig pc = new PackageConfig(); // pc.setModuleName(scanner("模块名")); pc.setParent("com.example.nacosprovider"); pc.setEntity("model"); pc.setMapper("mapper"); pc.setService("service"); pc.setServiceImpl("service.impl"); mpg.setPackageInfo(pc); // 自定义配置 // InjectionConfig cfg = new InjectionConfig() { // @Override // public void initMap() { // // to do nothing // } // }; // 如果模板引擎是 freemarker // String templatePath = "/templates/mapper.xml.ftl"; // 如果模板引擎是 velocity // String templatePath = "/templates/mapper.xml.vm"; // 自定义输出配置 // List<FileOutConfig> focList = new ArrayList<>(); // 自定义配置会被优先输出 // focList.add(new FileOutConfig(templatePath) { // @Override // public String outputFile(TableInfo tableInfo) { // // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!! // return projectPath + "/src/main/resources/mapper/" + pc.getModuleName() // + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML; // } // }); /* cfg.setFileCreate(new IFileCreate() { @Override public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) { // 判断自定义文件夹是否需要创建 checkDir("调用默认方法创建的目录"); return false; } }); */ // cfg.setFileOutConfigList(focList); // mpg.setCfg(cfg); // 配置模板 TemplateConfig templateConfig = new TemplateConfig(); // 配置自定义输出模板 //指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别 // templateConfig.setEntity("templates/entity2.java"); // templateConfig.setService(); // templateConfig.setController(); templateConfig.setXml(null); mpg.setTemplate(templateConfig); // 策略配置 StrategyConfig strategy = new StrategyConfig(); strategy.setNaming(NamingStrategy.underline_to_camel); strategy.setColumnNaming(NamingStrategy.underline_to_camel); strategy.setSuperEntityClass("com.baomidou.mybatisplus.extension.activerecord.Model"); strategy.setEntityLombokModel(true); strategy.setRestControllerStyle(true); strategy.setEntityLombokModel(true); // 公共父类 // strategy.setSuperControllerClass("com.baomidou.ant.common.BaseController"); // 写于父类中的公共字段 // strategy.setSuperEntityColumns("id"); strategy.setInclude(scanner("表名,多个英文逗号分割").split(",")); strategy.setControllerMappingHyphenStyle(true); strategy.setTablePrefix(pc.getModuleName() + "_"); mpg.setStrategy(strategy); //mpg.setTemplateEngine(new FreemarkerTemplateEngine()); mpg.execute(); } }
nacos中加入数据源的配置
spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://127.0.0.1:3306/mybatis_plus?useSSL=false&useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&serverTimezone=GMT%2B8 spring.datasource.username=root spring.datasource.password=123456 <!--数据源类型--> spring.datasource.type=com.zaxxer.hikari.HikariDataSource spring.datasource.hikari.maximum-pool-size=40 spring.datasource.hikari.minimum-idle=10 spring.datasource.hikari.idle-timeout=600000 spring.datasource.hikari.max-lifetime=1800000 spring.datasource.hikari.connection-timeout=500 spring.datasource.hikari.login-timeout=500 spring.datasource.hikari.validation-timeout=1000 spring.datasource.hikari.initialization-fail-timeout=1000 <!--控制台输出sql语句--> mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl mybatis-plus.mapper-locations=classpath*:/mapper/*Mapper.xml
代码演示
NacosProviderApplication
需要加入@MapperScan扫描路径
package com.example.nacosprovider; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; @EnableDiscoveryClient @SpringBootApplication @MapperScan("com.example.nacosprovider.mapper") public class NacosProviderApplication { public static void main(String[] args) { SpringApplication.run(NacosProviderApplication.class, args); } }
UserController
import com.example.nacosprovider.model.User; import com.example.nacosprovider.service.IUserService; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; /** * <p> * 前端控制器 * </p> * * @author astupidcoder * @since 2022-10-08 */ @RestController @RequestMapping("/user") public class UserController { private IUserService iUserService; public UserController(IUserService iUserService) { this.iUserService = iUserService; } @PostMapping("/getById") public User getById() { return iUserService.getById(1); // 调用了mybatis-plus封装的查询方法 } @PostMapping("/findAllUser") public List<User> findAllUser(){ return iUserService.findAllUser(); } }
UserServiceImpl
package com.example.nacosprovider.service.impl; import com.example.nacosprovider.model.User; import com.example.nacosprovider.mapper.UserMapper; import com.example.nacosprovider.service.IUserService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.springframework.stereotype.Service; import java.util.List; /** * <p> * 服务实现类 * </p> * * @author astupidcoder * @since 2022-10-08 */ @Service public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService { private UserMapper userMapper; public UserServiceImpl(UserMapper userMapper) { this.userMapper = userMapper; } @Override public List<User> findAllUser() { return userMapper.findAllUser(); } }
IUserService
package com.example.nacosprovider.service; import com.example.nacosprovider.model.User; import com.baomidou.mybatisplus.extension.service.IService; import java.util.List; /** * <p> * 服务类 * </p> * * @author astupidcoder * @since 2022-10-08 */ public interface IUserService extends IService<User> { public List<User> findAllUser(); }
UserMapper
package com.example.nacosprovider.mapper; import com.example.nacosprovider.model.User; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.springframework.stereotype.Repository; import java.util.List; /** * <p> * Mapper 接口 * </p> * * @author astupidcoder * @since 2022-10-08 */ @Repository public interface UserMapper extends BaseMapper<User> { public List<User> findAllUser(); }
UserMapper.xml
<?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.example.nacosprovider.mapper.UserMapper"> <!-- 查找用户信息 --> <select id="findAllUser" resultType="com.example.nacosprovider.model.User"> select * from user </select> </mapper>
查询结果
更改nacos配置数据库为test2,无需启动项目直接读取的是test2中的数据,由此也验证了nacos可以动态的进行配置管理
标签:spring,数据源,org,nacos,Spring,import,com,public From: https://www.cnblogs.com/Auge/p/16769367.html