To start building springCloud’s client service.

First, the SpringBoot project is also generated online.

IO/start.spring. IO /

Because, I built spingCloud+ Eureka + Swagger +mybatisPlus at one time, so this time, I will show you at one time.

Because this time, I need to add some new configuration files instead of just these three, I will first show you the directory of the services that have been set up successfully:

The first is the pom.xml file:

<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> The < version > 1.5.1. RELEASE < / version > < relativePath / > <! -- lookup parent from repository --> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <! <dependency> <groupId>org.mybatis.spring. Boot </groupId> < artifactId > mybatis - spring - the boot - starter < / artifactId > < version > 1.2.0 < / version > < / dependency > <! <dependency> <groupId>com.baomidou</groupId> < artifactId > mybatisplus - spring - the boot - starter < / artifactId > < version > 1.0.5 < / version > < / dependency > < the dependency > <groupId>com.baomidou</groupId> <artifactId>mybatis-plus</artifactId> <version>2.1.8</version> </dependency> <! <dependency> <groupId>org.apache.velocity</groupId> <artifactId> The < version > 1.7 < / version > < / dependency > <! --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> The < version > 5.1.6 < / version > < / dependency > <! <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <! --Herbnate entity dependency --> <dependency> <groupId>javax.persistence</groupId> <artifactId>persistence- API </artifactId> The < version > 1.0.2 < / version > < / dependency > <! -- Redis dependency --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>org.apache.commons</groupId>  <artifactId>commons-pool2</artifactId> </dependency> <! Lombok --> <dependency> <groupId>org.projectlombok</groupId> <artifactId> Lombok </artifactId> <scope>provided</scope> </dependency> <! - springCloud start relying on - > < the dependency > < groupId > org. Springframework. Cloud < / groupId > <artifactId>spring-cloud-starter</artifactId> </dependency> <! - srpingCloud eureka services rely on - > < the dependency > < groupId > org. Springframework. Cloud < / groupId > <artifactId>spring-cloud-starter-eureka</artifactId> </dependency> <! - srpingCloud eureka services registered - > < the dependency > < groupId > org. Springframework. Cloud < / groupId > < artifactId > spring - the cloud - starter - netflix - eureka - server < / artifactId > < version >. 2.0.0 RELEASE < / version > < / dependency > <! -- New dependencies, swaggerUI--> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> < version > 2.7.0 < / version > < / dependency > < the dependency > < groupId >. IO springfox < / groupId > < artifactId > springfox swagger - UI < / artifactId > < version > 2.7.0 < / version > < / dependency > <! Alibaba </groupId> <artifactId> Fastjson </artifactId> The < version > 1.1.41 < / version > < / dependency > <! Jsonwebtoken </groupId> <artifactId> JJWT </artifactId> <version>0.9.0</version> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-hystrix</artifactId> </dependency> <dependency> <groupId>com.netflix.hystrix</groupId> <artifactId>hystrix-javanica</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> </dependencies> <! -- Introduce spring Cloud dependencies, not less, <dependency management > <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>Edgware.RELEASE</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> <resources> <resource> <! <directory> SRC /main/resources</directory> <! --> <includes> <include>**/. XML </include> <include>**/. Properties </include> </includes> </resource> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering>
			</resource>
		</resources>

	</build>
Copy the code

In this POM file, there is also the dependency of Redis, which I will add later, but it has not been added at the present stage.

Application. The properties file

# service name
spring.application.name=permission
# port
server.port=2222
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Database informationspring.datasource.url: jdbc:mysql://localhost:3306/myblog? useUnicode=true&characterEncoding=utf-8&useSSL=falseSpring. The datasource. Username: root spring. The datasource. Password: 123456 (please fill in your database password) spring. The datasource. The driver - class - name: com.mysql.jdbc.Driver# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
spring.jmx.default-domain=${spring.application.name}
spring.jpa.open-in-view=false
# SpringFramework. web logs are output at DEBUG level
logging.level.org.springframework.web=info
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
Classpath :/com/blog/*/mapper/* mapper.xml
Mapper.xml :/ mapper.xml :/ mapper.xml
mybatis-plus.mapper-locations=classpath:/mapper/*Mapper.xml
# Entity scan, separate multiple packages with commas or semicolons
mybatis-plus.type-aliases-package=com.blog.*.entity
# Hump underline conversion
mybatis-plus.global-config.db-column-underline=true
# Refresh mapper debugger
mybatis-plus.global-config.refresh-mapper=false
# database uppercase underline conversion
mybatis-plus.global-config.capital-mode=true
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Configure Swagger information (from Eureka to Swagger page)
eureka.instance.prefer-ip-address=true
eureka.instance.hostname=:${spring.cloud.client.ipAddress}
eureka.instance.status-page-url:http://${spring.cloud.client.ipAddress}:${server.port}/swagger-ui.html
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Eureka registry path
eureka.client.service-url.defaultZone=http://localhost:1111/eureka/
# Indicates the heartbeat time that the service sends to eureka server
eureka.instance.leaseRenewalIntervalInSeconds: 10
The eureka server removes the cache of the service when the service is offline
eureka.instance.leaseExpirationDurationInSeconds: 2
The name of the service registered on Eureka
eureka.instance.instance-id=http://${spring.cloud.client.ipAddress}:${server.port}/${spring.application.name}
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Logical delete configuration (the following 3 configurations), not real delete data, just logical delete data
mybatis-plus.global-config.logic-delete-value=1
mybatis-plus.global-config.logic-not-delete-value=0
mybatis-plus.global-config.sql-injector=com.baomidou.mybatisplus.mapper.LogicSqlInjector
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
mybatis-plus.global-config.meta-object-handler=com.blog.permission.mabatisPlus.MyMetaObjectHandler
mybatis-plus.configuration.map-underscore-to-camel-case=true
mybatis-plus.configuration.cache-enabled=false
mybatis-plus.configuration.jdbc-type-for-null=null
mybatis-plus.typeAliasesPackage=com.blog.permission.entity
mybatis-plus.global-config.id-type=3
mybatis-plus.global-config.field-strategy=2
mybatis-plus.global-config.key-generator=com.baomidou.mybatisplus.incrementer.OracleKeyGenerator
Copy the code

Start the class PermissionApplication. Java file

Image:

@EnableWebSecurity
@SpringCloudApplication
@EnableTransactionManagement
@EnableFeignClients
@ComponentScan(basePackages = "com.blog.permission") @EnableAsync @EnableScheduling @EnableSwagger2 @EnableWebMvc public class PermissionApplication { public static void main(String[] args) { SpringApplication.run(PermissionApplication.class, args);; }}Copy the code

Next, it’s time to add a configuration file.

Swagger profile.

New configuration file: Swagger2.java

@Configuration
@EnableSwagger2
public class Swagger2 {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.blog.permission.controller"))
                .paths(Predicates.not(PathSelectors.regex("/error.*"Paths (PathSelectors. Regex (PathSelectors."/. *"Build (); } private ApiInfoapiInfo() {
        returnNew ApiInfoBuilder() // page title.title("Login and Permission Management 20190926"// description. Description ("Project API Documentation"// origin.contact ()"I am the author.") // Version number.version("1.0") .build(); }}Copy the code

Added the configuration file webmvcconfig.java

@Configuration
@EnableWebMvc
class WebMvcConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");

        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/"); } / / set the value of the responsebody swagger back inside for a json string @ Override public void configureMessageConverters (List < HttpMessageConverter <? >> converters){ MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); List<MediaType> list=new ArrayList<MediaType>(); list.add(MediaType.APPLICATION_JSON_UTF8); list.add(new MediaType("text"."html", Charset.forName("UTF-8")));
        list.add(new MediaType("application"."*+json",Charset.forName("UTF-8"))); converter.setSupportedMediaTypes(list); converters.add(converter); }}Copy the code

MybatisPlus configuration file

New configuration file: MybatisPlusConfig, Java

@EnableTransactionManagement
@Configuration
@MapperScan("com.blog.*.mapper"Public class MybatisPlusConfig {/** * mybatis-plus SQL execution efficiency */ @bean public PerformanceInterceptorperformanceInterceptor() {
        return new PerformanceInterceptor();
    }

    /*
     * 分页插件,自动识别数据库类型 多租户,请参考官网【插件扩展】
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }

    @Bean
    public MetaObjectHandler metaObjectHandler() {
        returnnew MyMetaObjectHandler(); } /** * inject primary key generator */ @bean public IKeyGeneratorkeyGenerator() {
        returnnew H2KeyGenerator(); } /** * inject SQL injector */ @bean public ISqlInjectorsqlInjector() {
        returnnew LogicSqlInjector(); }}Copy the code

New configuration file: mybatisplusSQL.java

public class MybatisPlusSql implements FactoryBean<SqlSessionFactory>, InitializingBean, ApplicationListener<ApplicationEvent> { private static final Log LOGGER = LogFactory.getLog(SqlSessionFactoryBean.class); private Resource configLocation; private Configuration configuration; private Resource[] mapperLocations; private DataSource dataSource; private TransactionFactory transactionFactory; private Properties configurationProperties; private SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder(); private SqlSessionFactory sqlSessionFactory; private String environment = SqlSessionFactoryBean.class.getSimpleName(); private boolean failFast; private Interceptor[] plugins; private TypeHandler<? > []typeHandlers;
    private String typeHandlersPackage; private Class<? > []typeAliases;
    private String typeAliasesPackage; private Class<? >typeAliasesSuperType;
    private DatabaseIdProvider databaseIdProvider;
    private Class<? extends VFS> vfs;
    private Cache cache;
    private ObjectFactory objectFactory;
    private ObjectWrapperFactory objectWrapperFactory;




    @Override
    public SqlSessionFactory getObject() throws Exception {
        returnnull; } @Override public Class<? >getObjectType() {
        return null;
    }

    @Override
    public boolean isSingleton() {
        return false;
    }

    @Override
    public void afterPropertiesSet() throws Exception {

    }

    @Override
    public void onApplicationEvent(ApplicationEvent applicationEvent) {

    }
}
Copy the code

New configuration file: MyMetaobjecthandler.java

@Component
public class MyMetaObjectHandler extends MetaObjectHandler {

    protected final static Logger logger = LoggerFactory.getLogger(Application.class);

    @Override
    public void insertFill(MetaObject metaObject) {
        logger.info("Add database:");
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        logger.info("Modify database:"); }}Copy the code

To avoid some boot-up errors, I also created a blank config.properties file with nothing in it.

Ok, the configuration file is almost complete, but if you start the service at this time, you will still get an error because you don’t have the corresponding controller, Serivice, Mapper, etc.

Therefore, I created an entity class that specifically generated the code.

Code generator: createcodeMethod.java

 @Component
public class CreateCodeMethod {
    /**
     *
     * @Title: main
     * @Description: 生成
     * @param args
     */
    public static void main(String[] args) {
        AutoGenerator mpg = new AutoGenerator();

        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        gc.setOutputDir("D://"); // Gc.setFileOverride (true);
        gc.setActiveRecord(false); // Change the ActiveRecord feature if it is not requiredfalse
        gc.setEnableCache(false); // gc.setBaseresultmap (true); // XML ResultMap gc.setBaseColumnList(false); // XML columList gc.setAuthor("wuchong"); // author // Customize the file name, note that %s will automatically populate the table entity attributes! gc.setControllerName("%sController");
        gc.setServiceName("%sService");
        gc.setServiceImplName("%sServiceImpl");
        gc.setMapperName("%sMapper");
        gc.setXmlName("%sMapper"); mpg.setGlobalConfig(gc); // DataSourceConfig DSC = new DataSourceConfig(); dsc.setDbType(DbType.MYSQL); dsc.setDriverName("com.mysql.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("123456");
        dsc.setUrl("jdbc:mysql://localhost:3306/myblog"); mpg.setDataSource(dsc); // StrategyConfig strategy = new StrategyConfig(); // strategy.setTablePrefix(new String[] {"sys_"}); // This can be changed to your table prefix strategy.setnaming (namingStrategy.underline_to_camel); Strategy. setInclude(new String[] {"permission"."permission_manage"."user"}); / / need to generate the table strategy. SetLogicDeleteFieldName ("record_status"); / / set the fields of logical deletion strategy. SetSuperServiceClass (null); strategy.setEntityLombokModel(true); strategy.setSuperServiceImplClass(null); strategy.setSuperMapperClass(null); mpg.setStrategy(strategy); PackageConfig PC = new PackageConfig(); pc.setParent("blog");
        pc.setController("controller");
        pc.setService("service");
        pc.setServiceImpl("service.impl");
        pc.setMapper("mapper");
        pc.setEntity("entity");
        pc.setXml("xml"); mpg.setPackageInfo(pc); // generate mpg.execute(); }}Copy the code

Mysql > alter table table_name (); mysql > alter table table_name ()

@TableLogic

With this annotation, when you call the delete method of mybatisPlus, it will logically delete your data.

Ok, I configured the generated Java files in the BLOG folder of disk D, took them out and put them into the project.

As shown in the figure:

Open the web page and type in the url: localhost:1111.

Click: http://192.168.1.5:2222/permission, you can into the swagger page, as shown in the figure below

conclusion

The Eureka client I built is actually satisfying the development needs of just playing by yourself.

The important thing to note is that you can create files to your liking, but make sure to pay attention to configuration files. For example, in the application.properties file there is a configuration like this: