Springboot builds microservice case Eureka registration center

1. Parent project dependency management

<?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>org.mumu</groupId>
    <artifactId>eureka</artifactId>
    <packaging>pom</packaging>
    <version>1.0</version>
    <modules>
        <module>common</module>
        <module>consumer</module>
        <module>springcloud-service-provider</module>
    </modules>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <junit.version>4.12</junit.version>
        <log4j.version>1.2.17</log4j.version>
        <mysql.version>5.1.47</mysql.version>
        <lombok.version>1.16.18</lombok.version>
        <druid.version>1.1.16</druid.version>
        <mybatis.spring.boot.version>1.3.0</mybatis.spring.boot.version>
    </properties>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
                <version>2.2.1.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
                <version>2.2.1.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-project-info-reports-plugin</artifactId>
                <version>3.0.0</version>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>2.2.2.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>${mysql.version}</version>
                <scope>runtime</scope>
            </dependency>
            <!-- <!- druid->-->
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid-spring-boot-starter</artifactId>
                <version>1.1.10</version>
            </dependency>
            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>${mybatis.spring.boot.version}</version>
            </dependency>
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>${junit.version}</version>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <addResources>true</addResources>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

2. Build the public module common

put some pojo class

1. Dependency introduction

<?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>eureka</artifactId>
        <groupId>org.mumu</groupId>
        <version>1.0</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>springcloud-service-common</artifactId>
    <version>1.0</version>
    <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>
            <version>1.18.30</version>
        </dependency>
    </dependencies>

</project>

2. Entity class

@Data // Omit the get set method
@NoArgsConstructor //Provide a parameterless constructor
@AllArgsConstructor //Provides a constructor with all parameters
public class Payment implements Serializable {

    private long id;
    private String serial;
}

3. Build a service provider

1. Dependency introduction

<?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>eureka</artifactId>
        <groupId>org.mumu</groupId>
        <version>1.0</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>springcloud-service-provider</artifactId>
    <version>1.0</version>
    <groupId>org.mumu</groupId>

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

    <dependencies>
        <dependency>
            <groupId>org.mumu</groupId>
            <artifactId>springcloud-service-common</artifactId>
            <version>1.0</version>
        </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>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
        </dependency>
        <!--mysql-connector-java-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <!--jdbc-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!--eureka-client-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
    </dependencies>

</project>

2. Configuration class

server:
  port: 8001 #Configure service port number
spring:
  application:
    name: service-provider # Configure the name of the service provider
  datasource: # Configure basic information for connecting to the database
    driver-class-name: com.mysql.jdbc.Driver # Driver
    url: jdbc:mysql://localhost:3306/cloud2023 # URL to connect to the database
    username: root # Username to connect to the database
    password: 123456 # Password to connect to the database
mybatis:
  config-location: classpath:/mybatis/sqlMapConfig.xml #Introduce the core configuration file of mybatis
  mapper-locations: classpath:/mybatis/mapper/*.xml #Introduce the mapping file of mybatis
eureka:
  client:
    register-with-eureka: true # Allow the current service to be registered to the eureka registration center
    fetch-registry: true # Allow the current microservice to pull service information from the registration center
    service-url:
      defaultZone: http://localhost:7001/eureka/,http://localhost:7002/eureka/ # The address of the eureka registration center

3. Write startup class

@SpringBootApplication
@MapperScan(basePackages = "com.xq.dao")
@EnableDiscoveryClient //Enable service discovery function
public class ProviderApplication {
    public static void main(String[] args) {
        SpringApplication.run(ProviderApplication.class,args);
    }
}

4. Write business logic

(1) Integrate mybatis

layer

public interface PaymentDao {

    //Query payment information based on id
    public Payment findById(long id);

    //Add payment information
    public void add(Payment payment);
}

Create the mapping file for the dao interface and the core configuration file of mybatis

<?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="org.mumu.dao.PaymentDao">

    <!--Query payment information based on id-->
    <select id="findById" parameterType="long" resultType="payment">
        SELECT * FROM `payment` WHERE id = #{id}
    </select>

    <!--Add payment information-->
    <insert id="add" parameterType="payment">
        INSERT INTO `payment`(`id`,`serial`) VALUES(#{id},#{serial})
    </insert>
</mapper>

Configure the type alias of MyBatis to simplify the configuration in the MyBatis mapping file

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!--Get an alias-->
    <typeAliases>
        <package name="org.mumu.pojo"></package>
    </typeAliases>
</configuration>

(2) Service

@Service
public class PaymentServiceImpl implements PaymentService {

    @Resource
    PaymentDao paymentDao;

    @Override
    public Payment findById(long id) {
        return paymentDao.findById(id);
    }

    @Override
    public void add(Payment payment) {
        paymentDao.add(payment);
    }

    @Override
    public void save(Payment payment) {
        paymentDao.add(payment);
    }
}

5. Define controller

@RestController
@RequestMapping("provider")
public class PaymentController {
    @Resource
    PaymentService paymentService;
    @Value("${server.port}")
    String port;

    @RequestMapping("findById")
    public Result<Payment> findById(@RequestParam("id") long id){
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Payment payment = paymentService.findById(id);
        return new Result<>(200, "Data query is successful, the current service port number is:" + this.port,payment);
    }
}

4. Build service consumer

1. Dependency introduction

<dependencies>
        <dependency>
            <groupId>org.mumu</groupId>
            <artifactId>springcloud-service-common</artifactId>
            <version>1.0</version>
        </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>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!--eureka-client-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
    </dependencies>

2. Configuration class

server:
  port: 80
spring:
  application:
    name: service-consumer
eureka:
  client:
    register-with-eureka: true # Allow the current service to be registered to the eureka registration center
    fetch-registry: true # Allow the current microservice to pull service information from the registration center
    service-url:
      defaultZone: http://localhost:7001/eureka/,http://localhost:7002/eureka/ # The address of the eureka registration center

3. Startup class

@SpringBootApplication
@EnableDiscoveryClient
public class ConsumerApplication {
    public static void main(String[] args) {
        SpringApplication.run(ConsumerApplication.class,args);
    }
}

4.InjectRestTemplate component intoioccontainer

use
RestTemplate
this
Java
Client component to implement remote invocation of services. So we need to

RestTemplate
use
Java
Configuration class for injection:

@Configuration
public class MyConfig {

    @Bean
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }

}

5. Define controller

@RestController
@RequestMapping("consumer")
@Slf4j
public class PaymentController {

   @Resource
   RestTemplate restTemplate;


    @RequestMapping("findById/{id}")
    public Result<Payment> findById(@PathVariable("id") long id){
        String url = "http://localhost:8001/provider/findById?id=" + id; //Maintain the ip + port of the service provider
        Result result = restTemplate.getForObject(url, Result.class);
        return result;
    }
}

5. Build a service registration center

1.Introduce dependent server

 <dependencies>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version> <!-- Use a version compatible with Tomcat 9.0.29 -->
        </dependency>
        <!--eureka server dependencies-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>

        <!--web launcher-->
        <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>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
    </dependencies>

2. Configuration class

There is no need to register the service here, because the server module of this module

Responsible for service registration for other Clients

server:
  port: 7001
# Configure eureka server
eureka:
  client:
    register-with-eureka: false # Prohibit yourself from registering yourself
    fetch-registry: false # Disable fetching service information in the registration center
    service-url:
      defaultZone: http://localhost:7001/eureka/ # The address of the eureka server

3. Startup class

@SpringBootApplication
@EnableEurekaServer //Identifies that the current service is the Eurkea server
public class EurekaServerApplication {
    public static void main(String[] args) {
        SpringApplication.run(EurekaServerApplication.class,args);
    }
}

6. Start

Access address: http://localhost:7001