更新时间:2024-03-07 GMT+08:00
分享

构建Spring Cloud工程

创建父工程

  1. 创建Maven工程。

    图1 创建Maven工程

  2. 父pom添加依赖。

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>2.2.8.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

创建子工程ServiceA

  1. 创建Maven工程。

    图2 创建Maven工程

  2. 新建src目录。

    图3 新建src目录

  3. 编写业务代码。

    图4 业务代码文件
    1. 编写启动类
      package com.huawei.demo.servicea;
      
      import org.springframework.boot.SpringApplication;
      import org.springframework.boot.autoconfigure.SpringBootApplication;
      import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
      
      /**
       * 启动类
       *
       * @author XXX
       * @since 2023-12-05
       */
      @SpringBootApplication
      @EnableEurekaClient
      public class ServiceASpringbootApplication {
          public static void main(String[] args) {
              SpringApplication.run(ServiceASpringbootApplication.class, args);
          }
      }
    2. 编写Controller类
      package com.huawei.demo.servicea.controller;
      
      import org.springframework.beans.factory.annotation.Autowired;
      import org.springframework.web.bind.annotation.GetMapping;
      import org.springframework.web.bind.annotation.PathVariable;
      import org.springframework.web.bind.annotation.RequestMapping;
      import org.springframework.web.bind.annotation.RestController;
      
      import com.huawei.demo.servicea.pojo.UserInfo;
      import com.huawei.demo.servicea.service.UserService;
      
      /**
       * 用户对外接口
       *
       * @author XXX
       * @since 2023-12-06
       */
      @RestController
      @RequestMapping("/user")
      public class UserController {
          @Autowired
          private UserService userService;
      
          @GetMapping("/{userId}")
          public UserInfo getUserByName(@PathVariable String userId) {
              return userService.getUserById(userId);
          }
      }
    3. 编写Mapper类
      package com.huawei.demo.servicea.mapper;
      
      import org.apache.ibatis.annotations.Mapper;
      import org.apache.ibatis.annotations.Select;
      
      import com.huawei.demo.servicea.pojo.UserInfo;
      
      /**
       * 用户查询
       *
       * @author XXX
       * @since 2023-12-06
       */
      @Mapper
      public interface UserMapper {
          @Select("select * from demo_user_info where user_id = #{userId}")
          UserInfo getUserById(String userId);
      }
    4. 编写Pojo类
      package com.huawei.demo.servicea.pojo;
      
      import lombok.Data;
      
      /**
       * user信息
       *
       * @author XXX
       * @since 2023-12-06
       */
      @Data
      public class UserInfo {
          private String userId;
      
          private String userName;
      
          private String phone;
      
          private String address;
      }
    5. 编写Service类
      package com.huawei.demo.servicea.service;
      
      import org.springframework.beans.factory.annotation.Autowired;
      import org.springframework.stereotype.Service;
      
      import com.huawei.demo.servicea.mapper.UserMapper;
      import com.huawei.demo.servicea.pojo.UserInfo;
      
      /**
       * userService
       *
       * @author XXX
       * @since 2023-12-06
       */
      @Service
      public class UserService {
          @Autowired
          private UserMapper userMapper;
      
          public UserInfo getUserById(String userId) {
              return userMapper.getUserById(userId);
          }
      }
    6. 配置微服务
      server:
        port: 8081
      spring:
        application:
          name: demoServiceA
        datasource:
          url: jdbc:mysql://127.0.0.1:3306/spring_cloud_demo?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
          username: root
          password: ***
          driver-class-name: com.mysql.jdbc.Driver
      
      mybatis:
        configuration:
          map-underscore-to-camel-case: true
        type-aliases-package: com.huawei.dmo.servicea

创建子工程ServiceB

  1. 创建Maven工程。

    图5 创建Maven工程

  2. 新建src目录。

    图6 新建src目录

  3. 编写业务代码。

    图7 业务代码文件
    1. 编写启动类
      package com.huawei.demo.serviceb;
      
      import org.springframework.boot.SpringApplication;
      import org.springframework.boot.autoconfigure.SpringBootApplication;
      import org.springframework.cloud.client.loadbalancer.LoadBalanced;
      import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
      import org.springframework.context.annotation.Bean;
      import org.springframework.web.client.RestTemplate;
      
      /**
       * 功能描述
       *
       * @author XXX
       * @since 2023-12-05
       */
      @SpringBootApplication
      @EnableEurekaClient
      public class ServiceBSpringbootApplication {
          public static void main(String[] args) {
              SpringApplication.run(ServiceBSpringbootApplication.class, args);
          }
      
          @Bean
          @LoadBalanced
          public RestTemplate restTemplate() {
              return new RestTemplate();
          }
      }
    2. 编写Controller类
      package com.huawei.demo.serviceb.controller;
      
      import org.springframework.beans.factory.annotation.Autowired;
      import org.springframework.web.bind.annotation.GetMapping;
      import org.springframework.web.bind.annotation.PathVariable;
      import org.springframework.web.bind.annotation.RequestMapping;
      import org.springframework.web.bind.annotation.RestController;
      
      import com.huawei.demo.serviceb.pojo.OrderInfo;
      import com.huawei.demo.serviceb.service.OrderService;
      
      /**
       * 用户对外接口
       *
       * @author XXX
       * @since 2023-12-06
       */
      @RestController
      @RequestMapping("/order")
      public class OrderController {
          @Autowired
          private OrderService orderService;
      
          @GetMapping("/{orderId}")
          public OrderInfo findOrder(@PathVariable String orderId) {
              return orderService.findOrder(orderId);
          }
      }
    3. 编写Domain类
      package com.huawei.demo.serviceb.domain;
      
      import lombok.Data;
      
      /**
       * user信息
       *
       * @author XXX
       * @since 2023-12-06
       */
      @Data
      public class UserInfo {
          private String userId;
      
          private String userName;
      
          private String phone;
      
          private String address;
      }
    4. 编写Mapper类
      package com.huawei.demo.serviceb.mapper;
      
      import org.apache.ibatis.annotations.Mapper;
      import org.apache.ibatis.annotations.Select;
      
      import com.huawei.demo.serviceb.pojo.OrderInfo;
      
      /**
       * 用户查询
       *
       * @author XXX
       * @since 2023-12-06
       */
      @Mapper
      public interface OrderMapper {
          @Select("select * from demo_order_info where order_id = #{orderId}")
          OrderInfo getOrderById(String orderId);
      }
    5. 编写Pojo类
      package com.huawei.demo.serviceb.pojo;
      
      import com.huawei.demo.serviceb.domain.UserInfo;
      
      import lombok.Data;
      
      /**
       * order信息
       *
       * @author XXX
       * @since 2023-12-06
       */
      @Data
      public class OrderInfo {
          private String orderId;
      
          private String orderName;
      
          private String price;
      
          private String userId;
      
          private UserInfo userInfo;
      }
    6. 编写Service类
      package com.huawei.demo.serviceb.service;
      
      import org.springframework.beans.factory.annotation.Autowired;
      import org.springframework.stereotype.Service;
      import org.springframework.web.client.RestTemplate;
      
      import com.huawei.demo.serviceb.domain.UserInfo;
      import com.huawei.demo.serviceb.mapper.OrderMapper;
      import com.huawei.demo.serviceb.pojo.OrderInfo;
      
      /**
       * 功能描述
       *
       * @author XXX
       * @since 2023-12-06
       */
      @Service
      public class OrderService {
      
          @Autowired
          private RestTemplate restTemplate;
      
          @Autowired
          private OrderMapper orderMapper;
      
          public OrderInfo findOrder(String orderId) {
              OrderInfo orderInfo=orderMapper.getOrderById(orderId);
              String url = "http://demoServiceA/user/" + orderInfo.getUserId();
              UserInfo userInfo = restTemplate.getForObject(url, UserInfo.class);
              orderInfo.setUserInfo(userInfo);
              return orderInfo;
          }
      }
    7. 配置微服务
      server:
        port: 8082
      spring:
        application:
          name: demoServiceB
        datasource:
          url: jdbc:mysql://127.0.0.1:3306/spring_cloud_demo?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
          username: root
          password: ***
          driver-class-name: com.mysql.jdbc.Driver
      
      eureka:
        client:
          service-url:
            defaultZone: http://localhost:11011/eureka/
      
      mybatis:
        configuration:
          map-underscore-to-camel-case: true
        type-aliases-package: com.huawei.dmo.servicea

创建Eureka注册中心

  1. 创建Eureka微服务。
  2. 添加依赖。

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
    </dependency>
    <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>

  3. 新建启动类。

    图8 新建启动类

  4. 启动类中增加注解@EnableEurekaServer,标明注册中心微服务。

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

  5. 在Eureka微服务中增加配置文件。

    图9 增加配置文件

  6. 配置注册中心微服务端口等。

    server:
      port: 11011
    spring:
      application:
        name: eureka
    
    eureka:
      client:
        register-with-eureka: false
        fetch-registry: false

  7. 其他微服务中增加注册中心配置。

    eureka:
      client:
        service-url:
          defaultZone: http://localhost:11011/eureka/

  8. 依次启动Eureka、DemoServiceA、DemoServiceB,访问http://localhost:11011/,可以看到DemoServiceA、DemoServiceB的信息。

    图10 查看微服务注册信息

  9. 调用接口:http://localhost:8082/order/1。

    图11 调用接口

相关文档