Simple Spring cloud microservice project construction

IDE development tools: IntelliJ IDEA 14.0.2

Version management: Maven

Technology stack: Spring Cloud

Environment: JDK 1.8

1. Create a Maven project

1. File——>New Project——>Maven as shown in the figure:

2. Fill in the module name and project path

 

Following the above steps, a Maven project is simply created.

At this point the project is not yet a SpringBoot project

2. Create sub-projects

Create sub-projects in the same way, note that the group name needs to be declared in pom. One of the simplest microservice project structures is as follows. Among them, common is extracted separately for entities, etc., and other projects use it as a module introduced since then. eureka-server is the eureka server, and other business modules must be registered as clients. system-management is an example of a business module, which implements a login interface.

3. Configure each module pom

1. Total project

Mainly manage the versions of modules and dependencies

groupId should be changed to the groupId when you create your own project

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.cloud</groupId>
    <artifactId>cloud-demo</artifactId>
    <version>1.0-SNAPSHOT</version>
    <modules>
        <module>eureka</module>
        <module>web-server</module>
        <module>common</module>
        <module>system-management</module>
    </modules>
    <packaging>pom</packaging>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <!--<version>1.5.6.RELEASE</version>-->
        <version>1.5.22.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>


    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>com.spotify</groupId>
                <artifactId>docker-maven-plugin</artifactId>
                <version>0.4.3</version>
                <configuration>
                    <skipDockerBuild>true</skipDockerBuild>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

2. common module

Parent needs to be specified as the artifactId of the total project

groupId should be changed to the groupId when you create your own project

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>cloud-demo</artifactId>
        <groupId>com.cloud</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>common</artifactId>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
    </dependencies>
</project>

3.eureka-server

Artifact and group names are the same

The core dependency is

eureka-server

Other dependencies are introduced according to code needs

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>cloud-demo</artifactId>
        <groupId>com.cloud</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>eureka</artifactId>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <spring-cloud.version>Edgware.SR6</spring-cloud.version>

    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka-server</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>



</project>

4. Microservice module

Artifact and group names are the same

The core dependencies are eureka client, Feign client, Springboot

and public modules

<?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>
        <artifactId>cloud-demo</artifactId>
        <groupId>com.cloud</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <artifactId>system-management</artifactId>
    <name>system-management</name>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <spring-cloud.version>Edgware.SR6</spring-cloud.version>
    </properties>


    <dependencies>
        <!--eureka客户端-->

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
        </dependency>

        <!--数据库配置-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.6</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.4</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.35</version>
        </dependency>

        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>




        <!--springboot配置-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>


        <!--Feign-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-feign</artifactId>
        </dependency>
        <!--公共模块-->
        <dependency>
            <groupId>com.cloud</groupId>
            <artifactId>common</artifactId>
            <version>1.0-SNAPSHOT</version>
            <scope>compile</scope>
        </dependency>

    </dependencies>



    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

</project>

5.Feign

The core dependency is

Eureka client, Feign server, Springboot, public modules

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>cloud-demo</artifactId>
        <groupId>com.cloud</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>web-server</artifactId>
    <packaging>jar</packaging>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <spring-cloud.version>Edgware.SR6</spring-cloud.version>
    </properties>
    <dependencies>



        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-feign</artifactId>
        </dependency>
        <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-eureka</artifactId>
        </dependency>


        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>


        <dependency>
            <groupId>com.cloud</groupId>
            <artifactId>common</artifactId>
            <version>1.0-SNAPSHOT</version>
            <scope>compile</scope>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
</project>

Four, configure yml

1.eureka-server

The main function is to configure the port number

server:
  port: 7001
eureka:
  instance:
    hostname: eureka7001.com #eureka服务端的实例名称
  client:
    register-with-eureka: false     #false表示不向注册中心注册自己。
    fetch-registry: false     #false表示自己端就是注册中心,我的职责就是维护服务实例,并不需要去检索服务
    service-url:
      #设置与eureka  server交互的地址和注册服务都需要依赖这个地址
      defaultZone: http://eureka7001.com:7001/eureka/  #单机就是指向自己

2. Microservice module

The main function is to configure the port number and mybatis and database

server.port=8099
#server.servlet.context-path=/disk
#spring.web.resources.static-locations=classpath:/templates/, classpath:/static/

spring.application.name=system-management

# MyBatis Configuration
mybatis.mapper-locations=classpath:mapper/*Mapper.xml
mybatis.type-aliases-package=import com.cloud.pojo


# Database Configuration
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=123456

3.Feign

Just configure the port number

The location of each configuration file is as follows

Among them, system-management is a microservice module, and web-server is Feign

yml is in the resources directory of each module, and pom is in the root directory of each module

It is best to understand the role of each dependency and configuration item, and it will help to solve problems if they occur.

The version is best managed in a unified manner.

5. Business code writing

1. eureka launcher

package com.buba.springcloud.eureka;
 
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
 
 
@SpringBootApplication
@EnableEurekaServer
public class EurekaMain {
    public static void main(String[] args) {
        SpringApplication.run(EurekaMain.class,args);
    }
}

2. Microservice Enabler

package com.study.springcloud.systemmanagement;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;


@SpringBootApplication
@EnableEurekaClient


public class SystemManagementApplication {

    public static void main(String[] args) {
        SpringApplication.run(SystemManagementApplication.class, args);
    }

}

3. Feign Launcher

package com.cloud;


import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
import org.springframework.context.annotation.ComponentScan;

//@ComponentScan(basePackages = {"com.study.springcloud.feign"})
//@EnableDiscoveryClient
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients

//@EnableFeignClients(basePackages = "com.cloud.client")
//@EnableFeignClients(basePackages = {"com.cloud"})

public class WebServerApplication {
    public static void main(String[] args) {

        SpringApplication.run(WebServerApplication.class, args);
    }
}

4. Public class

package com.cloud.pojo;

public class User {
    private int id;
    private String username;
    private String password;

    public User() {
    }
    public User(String username, String password){
        this.username=username;
        this.password=password;
    }


    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

}

5.Feign

5.1FeignClient

package com.cloud.client;


import com.cloud.pojo.User;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;


@FeignClient(name="system-management",url = "http://localhost:8099")
public interface LoginClient {

    @RequestMapping(value = "/login",method = RequestMethod.GET)
    boolean Login(@RequestParam("username") String username, @RequestParam("password") String password);
}

5.2 Controller 

package com.cloud.controller;



import com.cloud.pojo.User;
import com.cloud.client.LoginClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/webs")

public class LoginController {

    @Autowired
    private LoginClient loginClient;

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String Login(HttpServletRequest request){
        //System.out.println("ok");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        System.out.println("请求中username=:"+username);
        User user=new User(username,password);
        System.out.println("读取请求参数构造的user对象:"+user);
        System.out.println("读取请求参数构造的user对象的username:"+user.getUsername());
        if(loginClient.Login(user.getUsername(),user.getPassword())){
            return "success";
        }
        return "failed";
    }


}

6. Microservices

6.1Controller

package com.study.springcloud.systemmanagement.controller;

import com.cloud.pojo.User;
import com.study.springcloud.systemmanagement.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping
public class LoginController {

    @Autowired
    private LoginService loginService;

    //@RequestMapping(value = "/login", method = RequestMethod.GET)
    @RequestMapping(value = "/login",method = RequestMethod.GET)
    @ResponseBody
    public boolean login(String username,String password) {
//        System.out.println("传给微服务的user:"+user);
//        System.out.println("传给微服务的user的username:"+user.getUsername());
        System.out.println("传给微服务的username:"+username);
        User user_result = this.loginService.login(username, password);
        //System.out.println(user_result);
        return user_result != null;

    }
}




6.2Service

package com.study.springcloud.systemmanagement.service;

import com.cloud.pojo.User;

public interface LoginService {
    User login(String username, String password);
}

6.3Service instantiation

package com.study.springcloud.systemmanagement.controller;

import com.cloud.pojo.User;
import com.study.springcloud.systemmanagement.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping
public class LoginController {

    @Autowired
    private LoginService loginService;

    //@RequestMapping(value = "/login", method = RequestMethod.GET)
    @RequestMapping(value = "/login",method = RequestMethod.GET)
    @ResponseBody
    public boolean login(String username,String password) {
//        System.out.println("传给微服务的user:"+user);
//        System.out.println("传给微服务的user的username:"+user.getUsername());
        System.out.println("传给微服务的username:"+username);
        User user_result = this.loginService.login(username, password);
        //System.out.println(user_result);
        return user_result != null;

    }
}




6.4 Dao

package com.study.springcloud.systemmanagement.dao;

import com.cloud.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;

@Mapper
public interface UserDao {

    User login(@Param("username") String username, @Param("password") String password);
}

6.5 mapper.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.study.springcloud.systemmanagement.dao.UserDao">

    <resultMap id="userMap" type="User">
        <result property="username" column="username"/>
        <result property="password" column="password"/>
    </resultMap>

    <select id="login" resultMap="userMap">
        select username,password
        from user
        where username =#{username} and password =#{password}
    </select>


</mapper>

6. Project operation and verification using postman

All three services can be started

Tested by postman

The information printed on the console is also normal

 

 7. Summary

It is best to have a preliminary understanding of springboot, springcloud architecture, and the functions of each component, and try to build after understanding common dependencies.

The following is the author's personal understanding, please correct me.

When building, pay attention to changing the parameters of each configuration file to your own.

It is best to use a unified version of the management tool to avoid errors.

 Be patient, the beginning is hard.

The author encountered many mistakes when building, and they were solved step by step.

For example, the dao path of mapper.xml configuration is wrong (no error will be reported, it is difficult to find);

The EnableFeignClients annotation cannot scan FeignClient because the version is incompatible, and the project can only be solved after the overall refactoring of the project and the unified version of each module (Springboot and Springcloud components also have compatibility issues);

When Feign passes parameters to microservices, the value cannot be passed, because the method parameter of FeignClient is default, and the underlying principle is not yet known.

Guess you like

Origin blog.csdn.net/wjqsm/article/details/123479905