ToB企服应用市场:ToB评测及商务社交产业平台

标题: Spring Boot整合eureka和config搭建微服务框架(入门) [打印本页]

作者: 王國慶    时间: 2024-9-30 15:02
标题: Spring Boot整合eureka和config搭建微服务框架(入门)
        近来打仗了公司内部开发的项目,涉及到了Config设置中心河eureka服务注册中心,从前只用过Nacos服务设置中心,以是边学边试搭建了一个简朴的微服务的项目框架,同时记录一下自己踩过的坑。注:该demo中使用了远程调用服务,以是引入了Feign调用。
1.从零到一搭建项目

        首先创建一个maven项目,在这里我们构建一个父子项目,拆分为四个子项目:order、product、config、eureka,具体的项目结构如下:

        父程序pom依靠如下:
  1.   <properties>
  2.         <java.version>1.8</java.version>
  3.         <maven.compiler.source>8</maven.compiler.source>
  4.         <maven.compiler.target>8</maven.compiler.target>
  5.         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  6.         <spring-cloud.version>2021.0.1</spring-cloud.version>
  7.         <spring-cloud-alibaba.version>2022.0.0.0-RC2</spring-cloud-alibaba.version>
  8.         <mybatis-spring-boot-starter.version>3.0.2</mybatis-spring-boot-starter.version>
  9.         <spring-boot.version>2.6.4</spring-boot.version>
  10.         <mybatis-plus.version>3.5.3.1</mybatis-plus.version>
  11.         <hutool-all.version>5.8.20</hutool-all.version>
  12.         <mysql.version>8.0.33</mysql.version>
  13.     </properties>
  14.     <dependencies>
  15.         <dependency>
  16.             <groupId>org.projectlombok</groupId>
  17.             <artifactId>lombok</artifactId>
  18.         </dependency>
  19.         <dependency>
  20.             <groupId>cn.hutool</groupId>
  21.             <artifactId>hutool-all</artifactId>
  22.         </dependency>
  23.     </dependencies>
  24.     <dependencyManagement>
  25.         <dependencies>
  26.             <dependency>
  27.                 <groupId>org.springframework.boot</groupId>
  28.                 <artifactId>spring-boot-dependencies</artifactId>
  29.                 <version>${spring-boot.version}</version>
  30.                 <type>pom</type>
  31.                 <scope>import</scope>
  32.             </dependency>
  33.             <dependency>
  34.                 <groupId>org.springframework.cloud</groupId>
  35.                 <artifactId>spring-cloud-dependencies</artifactId>
  36.                 <version>${spring-cloud.version}</version>
  37.                 <type>pom</type>
  38.                 <scope>import</scope>
  39.             </dependency>
  40.             <dependency>
  41.                 <groupId>com.alibaba.cloud</groupId>
  42.                 <artifactId>spring-cloud-alibaba-dependencies</artifactId>
  43.                 <version>${spring-cloud-alibaba.version}</version>
  44.                 <type>pom</type>
  45.                 <scope>import</scope>
  46.             </dependency>
  47.             <dependency>
  48.                 <groupId>com.baomidou</groupId>
  49.                 <artifactId>mybatis-plus-boot-starter</artifactId>
  50.                 <version>${mybatis-plus.version}</version>
  51.             </dependency>
  52.             <dependency>
  53.                 <groupId>org.springframework.boot</groupId>
  54.                 <artifactId>spring-boot-starter-jdbc</artifactId>
  55.                 <version>${spring-boot.version}</version>
  56.             </dependency>
  57.             <dependency>
  58.                 <groupId>cn.hutool</groupId>
  59.                 <artifactId>hutool-all</artifactId>
  60.                 <version>${hutool-all.version}</version>
  61.             </dependency>
  62.             <dependency>
  63.                 <groupId>mysql</groupId>
  64.                 <artifactId>mysql-connector-java</artifactId>
  65.                 <version>${mysql.version}</version> <!-- 最新稳定版本 -->
  66.             </dependency>
  67.         </dependencies>
  68.     </dependencyManagement>
复制代码
        如果要改成自己的版本依靠,必要注意Spring Boot、Spring Cloud和eureka之间的对应关系,建议确定其中两个依靠的版本,然后由Maven自动引入剩余依靠。
2.构建eureka服务

2.1 服务包结构和设置

        项目标启动序次是eureka->config->其他微服务,因为其他服务必要向eureka注册中心注册服务,以是在这里先搭建eureka注册中心。
        eureka微服务结构如下:

        eureka-server的pom文件如下:
  1. <dependencies>
  2.         <dependency>
  3.             <groupId>org.springframework.cloud</groupId>
  4.             <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
  5.         </dependency>
  6.         <dependency>
  7.             <groupId>org.springframework.boot</groupId>
  8.             <artifactId>spring-boot-starter-web</artifactId>
  9.         </dependency>
  10.     </dependencies>
复制代码
        application.yml:
  1. spring:
  2.   application:
  3.     name: eureka-server
  4. server:
  5.   port: 8761
  6. eureka:
  7.   instance:
  8.     hostname: 127.0.0.1
  9.   client:
  10.     register-with-eureka: false
  11.     fetch-registry: false
  12.     service-url:
  13.       default-Zone: http://127.0.0.1:8761/eureka
复制代码
2.2 eureka设置注意事项


  1. Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.
  2. Reason: Failed to determine a suitable driver class
复制代码
该问题出现的缘故原由是引入了spring-boot-starter-jdbc 的依靠,但是并没有正确设置数据库,可以在启动类注解中加入@SpringBootApplication(exclude = DataSourceAutoConfiguration.class),去撤除数据库资源的自动扫描。



3.构建config设置中心

3.1 服务包结构和设置

        config设置中心用来存放其他微服务的设置文件,当其他微服务启动时,从设置中心拉取设置文件,完成服务启动。在该demo中,我将项目设置文件存储到了本地,并没有利用git存储到云端。项目包结构如下:

        将其他服务的设置文件放在了config目次下,同时必要在config设置文件中注明路径,xxx-test.yml表现测试环境下的设置,xxx-dev.yml表现开发环境下的设置,xxx-release.yml表现生产环境下的设置。在这里我仅引入了两个服务的dev环境下的设置。
        pom文件如下:
  1.         <!--eureka 客户端 -->
  2.         <dependency>
  3.             <groupId>org.springframework.cloud</groupId>
  4.             <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
  5.         </dependency>
  6.         <dependency>
  7.             <groupId>org.springframework.boot</groupId>
  8.             <artifactId>spring-boot-starter-web</artifactId>
  9.         </dependency>
  10.         <dependency>
  11.             <groupId>org.springframework.cloud</groupId>
  12.             <artifactId>spring-cloud-config-server</artifactId>
  13.         </dependency>
复制代码
        applictaion.yml如下,profiles.active=native表现设置文件存储在本地,cloud.config.server.native.search-locations表现设置文件存储的位置,即位于上一级目次的config目次下。
  1. server:
  2.   port: 8888
  3. spring:
  4.   application:
  5.     name: config-server
  6.   profiles:
  7.     active: native
  8.   cloud:
  9.     config:
  10.       server:
  11.         native:
  12.           search-locations:  file:./config/,classpath:/config/
  13. eureka:
  14.   client:
  15.     service-url:
  16.       defaultZone: http://localhost:8761/eureka
复制代码
        config目次下的设置文件,我仅仅进行了数据库设置, 如下:
  1. spring:
  2.   datasource:
  3.     username: root
  4.     password: ********
  5.     url: jdbc:mysql://ip:port/database_name?characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&transformedBitIsBoolean=true&serverTimezone=GMT%2B8
  6.     driver-class-name: com.mysql.cj.jdbc.Driver
  7.     hikari:
  8.       connection-test-query: select 1
  9.       connection-timeout: 20000
  10.       idle-timeout: 300000
  11.       maximum-pool-size: 5
  12.       minimum-idle: 5
复制代码
 3.2 config设置注意事项


  1. <dependency>
  2.    <groupId>org.springframework.cloud</groupId>
  3.    <artifactId>spring-cloud-config-server</artifactId>
  4. </dependency>
复制代码


 4.构建order服务

4.1 order服务包结构和设置

        在该项目demo中,order服务远程调用product服务,获取商品名和商品价格。以是应当在order服务启动类上加上@EnableFeignClients。order-server的项目结构如下:

         pom文件如下:
  1.      <dependencies>
  2.         <!--eureka 客户端 -->
  3.         <dependency>
  4.             <groupId>org.springframework.cloud</groupId>
  5.             <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
  6.         </dependency>
  7.         <dependency>
  8.             <groupId>org.springframework.boot</groupId>
  9.             <artifactId>spring-boot-starter-web</artifactId>
  10.         </dependency>
  11.         <dependency>
  12.             <groupId>org.springframework.cloud</groupId>
  13.             <artifactId>spring-cloud-starter-openfeign</artifactId>
  14.         </dependency>
  15.         <dependency>
  16.             <groupId>cn.hutool</groupId>
  17.             <artifactId>hutool-all</artifactId>
  18.         </dependency>
  19.         <dependency>
  20.             <groupId>org.projectlombok</groupId>
  21.             <artifactId>lombok</artifactId>
  22.         </dependency>
  23.         <dependency>
  24.             <groupId>com.baomidou</groupId>
  25.             <artifactId>mybatis-plus-boot-starter</artifactId>
  26.         </dependency>
  27.         <dependency>
  28.             <groupId>mysql</groupId>
  29.             <artifactId>mysql-connector-java</artifactId>
  30.             <!-- 版本可以省略,因为已经在父项目中定义 -->
  31.         </dependency>
  32.         <!--配置中心客户端 -->
  33.         <dependency>
  34.             <groupId>org.springframework.cloud</groupId>
  35.             <artifactId>spring-cloud-starter-config</artifactId>
  36.         </dependency>
  37.         <dependency>
  38.             <groupId>org.springframework.cloud</groupId>
  39.             <artifactId>spring-cloud-starter-bootstrap</artifactId>
  40.         </dependency>
  41.     </dependencies>
复制代码
        设置文件的启动序次为bootstrap.yml->application.yml->设置中心设置,同时后续的设置会覆盖从前的设置,注意eureka注册服务名均为大写,bootstrap.yml和application.yml文件如下:
        bootstrap.yml:
  1. spring:
  2.   cloud:
  3.     config:
  4.       discovery:
  5.         enabled: true
  6.         service-id: CONFIG-SERVER
  7.       name: ${spring.application.name}
  8.       profile: ${spring.profiles.active}
  9.       fail-fast: true
  10. eureka:
  11.   client:
  12.     service-url:
  13.       default-zone: http://127.0.0.1:8761/eureka
  14.     registry-fetch-interval-seconds: 30
复制代码
        application.yml:
  1. server:
  2.   port: 8081
  3. spring:
  4.   application:
  5.     name: order-server
  6.   profiles:
  7.     active: dev
复制代码
        在bootstrap.yml中的config设置中指定了设置中心的服务id为CONFIG-SERVER,设置中心名称为order-server,设置环境为dev。
4.2 order服务设置注意事项


  1. Application failed to start due to an exception
  2. org.springframework.cloud.commons.ConfigDataMissingEnvironmentPostProcessor$ImportException: No spring.config.import set
复制代码
5. 构建product服务

5.1 product服务包结构和设置

        product服务包结构如下:

         pom文件如下:
  1.      <dependencies>
  2.         <!--eureka 客户端 -->
  3.         <dependency>
  4.             <groupId>org.springframework.cloud</groupId>
  5.             <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
  6.         </dependency>
  7.         <dependency>
  8.             <groupId>org.springframework.boot</groupId>
  9.             <artifactId>spring-boot-starter-web</artifactId>
  10.         </dependency>
  11.         <dependency>
  12.             <groupId>org.springframework.cloud</groupId>
  13.             <artifactId>spring-cloud-starter-openfeign</artifactId>
  14.         </dependency>
  15.         <dependency>
  16.             <groupId>cn.hutool</groupId>
  17.             <artifactId>hutool-all</artifactId>
  18.         </dependency>
  19.         <dependency>
  20.             <groupId>org.projectlombok</groupId>
  21.             <artifactId>lombok</artifactId>
  22.         </dependency>
  23.         <dependency>
  24.             <groupId>com.baomidou</groupId>
  25.             <artifactId>mybatis-plus-boot-starter</artifactId>
  26.         </dependency>
  27.         <dependency>
  28.             <groupId>mysql</groupId>
  29.             <artifactId>mysql-connector-java</artifactId>
  30.             <!-- 版本可以省略,因为已经在父项目中定义 -->
  31.         </dependency>
  32.         <!--配置中心客户端 -->
  33.         <dependency>
  34.             <groupId>org.springframework.cloud</groupId>
  35.             <artifactId>spring-cloud-starter-config</artifactId>
  36.         </dependency>
  37.         <dependency>
  38.             <groupId>org.springframework.cloud</groupId>
  39.             <artifactId>spring-cloud-starter-bootstrap</artifactId>
  40.         </dependency>
  41.     </dependencies>
复制代码
         bootstrap.yml文件如下:
  1. spring:
  2.   cloud:
  3.     config:
  4.       discovery:
  5.         enabled: true
  6.         service-id: CONFIG-SERVER
  7.       name: ${spring.application.name}
  8.       profile: ${spring.profiles.active}
  9.       fail-fast: true
  10. eureka:
  11.   client:
  12.     service-url:
  13.       default-zone: http://localhost:8761/eureka
  14.     registry-fetch-interval-seconds: 30
复制代码
        application.yml文件如下:
  1. server:
  2.   port: 8080
  3. spring:
  4.   application:
  5.     name: product-server
  6.   profiles:
  7.     active: dev
复制代码
 6. 编写product服务代码

6.1 数据库设计

  1. DROP TABLE IF EXISTS `product`;
  2. CREATE TABLE `product`  (
  3.   `id` int(0) NOT NULL AUTO_INCREMENT,
  4.   `name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
  5.   `price` decimal(10, 2) NOT NULL,
  6.   `stock` int(0) NOT NULL,
  7.   PRIMARY KEY (`id`) USING BTREE
  8. ) ENGINE = InnoDB AUTO_INCREMENT = 5 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;
  9. -- ----------------------------
  10. -- Records of product
  11. -- ----------------------------
  12. INSERT INTO `product` VALUES (1, 'Laptop', 999.99, 10);
  13. INSERT INTO `product` VALUES (2, 'Smartphone', 499.99, 50);
  14. INSERT INTO `product` VALUES (3, 'Tablet', 299.99, 30);
  15. INSERT INTO `product` VALUES (4, 'Headphones', 79.99, 100);
  16. INSERT INTO `product` VALUES (5, 'Smartwatch', 199.99, 25);
复制代码
6.2 编写启动类

        因为order为服务发起方,product服务为被调用方,以是product服务仅必要添加@SpringBootApplication和@MapperScan两个注解。
6.3 编写商品服务controller层

        productController代码如下,编写了一个简朴api,通过id获取商品信息
  1. @RestController
  2. public class ProductController {
  3.    
  4.     @Resource
  5.     private ProductService productService;
  6.    
  7.     @GetMapping("/api/product/getProduct")
  8.     public ProductRespDTO product(@RequestParam("id")Integer id){
  9.         return productService.getProductById(id);
  10.     }
  11. }
复制代码
6.4 编写商品服务Service层

       ProductService代码如下:
  1. public interface ProductService {
  2.     ProductRespDTO getProductById(Integer id);
  3. }
复制代码
6.5 编写商品服务Service实现层

        ProductServiceImpl代码如下,这里没有做复杂的逻辑处理,直接查数据库返回结果。我使用的是mybatis-plus,自带的函数,可以用其他取代。
  1. @Service
  2. public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO>implements ProductService {
  3.    
  4.     @Override
  5.     public ProductRespDTO getProductById(Integer id) {
  6.         LambdaQueryWrapper<ProductDO> queryWrapper = Wrappers.lambdaQuery(ProductDO.class)
  7.           .eq(ProductDO::getId, id);
  8.         ProductDO productDO = baseMapper.selectOne(queryWrapper);
  9.         ProductRespDTO result=new ProductRespDTO();
  10.         BeanUtil.copyProperties(productDO,result);
  11.         return result;
  12.     }
  13. }
复制代码
6.6 编写商品服务Dao层实体和mapper接口

        引入lombok,利用在线网站天生实体类,网站地点:凝聚力开发,实体类如下:
  1. @Data
  2. @Builder
  3. @AllArgsConstructor
  4. @NoArgsConstructor
  5. @TableName("product")
  6. public class ProductDO {
  7.     private Integer id;          // 产品 ID
  8.     private String name;         // 产品名称
  9.     private BigDecimal price;    // 产品价格
  10.     private Integer stock;       // 产品库存
  11. }
复制代码
        mapper层接口如下:
  1. @Mapper
  2. public interface ProductMapper extends BaseMapper<ProductDO> {
  3. }
复制代码
6.7 请求返回实体类

        ProductRespDTO实体,仅返回商品的名称和价格。
  1. @Data
  2. @Builder
  3. @AllArgsConstructor
  4. @NoArgsConstructor
  5. public class ProductRespDTO {
  6.     private String name;         // 产品名称
  7.     private BigDecimal price;    // 产品价格
  8. }
复制代码
7. 编写Order服务

7.1 编写订单服务启动类

        Order服务必要远程调用Product服务,以是这里涉及到Feign调用。OrderApplication.class如下:
  1. @SpringBootApplication
  2. @EnableFeignClients
  3. public class OrderApplication {
  4.     public static void main(String[] args) {
  5.         SpringApplication.run(OrderApplication.class,args);
  6.     }
  7. }
复制代码
7.2 编写订单服务controller层

  1. @RestController
  2. public class OrderController {
  3.     @Resource
  4.     private ProductFeignClient productFeignClient;
  5.     @GetMapping("/api/getOrder")
  6.     public ProductRespDTO getProduct(@RequestParam("id")Integer id){
  7.         return productFeignClient.getProduct(id);
  8.     }
  9. }
复制代码
7.3 编写订单服务返回实体类

  1. @Data
  2. @Builder
  3. @AllArgsConstructor
  4. @NoArgsConstructor
  5. public class ProductRespDTO {
  6.     private String name;         // 产品名称
  7.     private BigDecimal price;    // 产品价格
  8. }
复制代码
7.4 编写远程调用接口

        注意,因为在eureka服务注册中心默认注册服务名为大写,以是引入也必要用大写,同时注意远程调用的接口路径必要与被调用api的路径一致,具体代码如下:
  1. @FeignClient(value = "PRODUCT-SERVER")
  2. public interface ProductFeignClient {
  3.     @GetMapping("/api/product/getProduct")
  4.     ProductRespDTO getProduct(@RequestParam("id")Integer id);
  5. }
复制代码
8. 总结

        微服务启动序次为:eureka->config->order/product。在后续项目启动之后可从eureka注册服务中心查看微服务注册情况,可直接访问对应接口传参进行测试。
        例如,可使用apifox大概postman对接口测试,来查看微服务搭建情况:

        

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。




欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4