开发者

SpringCloud服务实现同时使用eureka和nacos方法

目录
  • 一,背景
  • 二,代理服务创建和配置
    • 2.1 pom.XML
    • 2.2 bootstrap.yml
    • 2.3 Application.Java
    • 2.4 创建接口
      • 2.4.1 ApiMessageController.java
      • 2.4.2 MyNacosProperties.java
    • 2.5 运行测试
    • 三,将该服务引入eureka注册中心

      一,背景

      之所以会想到一个服务同时使用eureka和nacos,是因为遇到一个需求,配置数据是存储在nacos的配置中,然后使用该配置的服务却是在一个eureka环境中。所以此时就需要一个代理服务,它既能够从nacos的config中获取配置数据,又是注册到eureka注册中心中。

      二,代理服务创建和配置

      2.1 pom.xml

      <?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>lmc-tools</artifactId>
              <groupId>com.lmc</groupId>
              <version>1.0-SNAPSHOT</version>
          </parent>
          <modelVersion>4.0.0</modelVersion>
          <artifactId>tools-2-eureka-nacos</artifactId>
          <properties>
              <maven.compiler.source>8</maven.compiler.source>
              <maven.compiler.target>8</maven.compiler.target>
          </properties>
          <dependencies>
              <dependency>
                  <groupId>com.lmc</groupId>
                  <artifactId>tools-common</artifactId>
                  <version>1.0-SNAPSHOT</version>
              </dependency>
              <dependency>
                  <groupId>org.springframework.cloud</groupId>
                  <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
              </dependency>
      <!--        <dependency>-->
      <!--            <groupId>com.alijavascriptbaba.cloud</groupId>-->
      <!--            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>-->
      <!--            <version>2021.1</version>-->
      <!--        </dependency>-->
              <dependency>
                  <groupId>com.alibaba.cloud</groupId>
                  <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
                  <version>2021.1</version>
              </dependency>
              <dependency>
                  <groupId>org.springframework.cloud</groupId>
                  <artifactId>spring-cloud-starter-bootstrap</artifactId>
                  <version>3.1.1</version>
              </dependency>
              <dependency>
                  <groupId>org.springframework.boot</groupId>
                  <artifactId>spring-boot-starter-web</artifactId>
              </dependency>
          </dependencies>
      </project>

      注意,关于nacos,在该服务中不能引入spring-cloud-starter-alibaba-nacos-discovery依赖,只需要引入spring-cloud-starter-alibaba-nacos-config

      2.2 bootstrap.yml

      server:

        port: 9006

        servlet:

          context-path: /eureka-proxy

      spring:

        application:

          name: tools-eureka-proxy

        profiles:

          active: dev

      management:

        endpoints:

          web:

            exposure:

              include: "*"

      bootstrap-dev.yml

      spring:

        cloud:

          nacos:

            server-addr: localhost:9000

            config:

              namespace: 8628e5dd-a236-4016-b94f-565a001faf2f

              file-extension: yaml  # 配置内容的数据格式

              extension-configs[0]:

                data-id: ${spring.application.name}-${spring.profiles.active}.${spring.cloud.nacos.config.file-extension}

                group: dev

                refresh: true

      eureka:

        client:

          service-url:

            defaultZone: http://localhost:8761/eureka

          registry-fetch-interval-seconds: 10

        instance:

          instance-id: ${spring.application.name}:${spring.cloud.client.ip-address}:${server.port} # 实例名:application:ip:port

          prefer-ip-address: true # 优先使用IP地址作为主机名的标识

          lease-renewal-interval-in-seconds: 180 # 续约更新时间间隔

          lease-expiration-duration-in-seconds: 200

      2.3 Application.java

      package per.lmc.tools2.eureka;
      import org.springframework.b开发者_开发入门oot.SpringApplication;
      import org.springframework.boot.autoconfigure.SpringBootApplication;
      import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
      /**
       * @Description: TODO
       * @version: 1.0
       */
      @SpringBootApplication
      @EnableDiscoveryClient
      public class EurekaProxyApplication {
          public static void main(String[] args) {
              SpringApplication.run(EurekaProxyApplication.class, args);
          }
      }
      

      2.4 创建接口

      2.4.1 ApiMessageController.java

      package per.lmc.tools2.eureka.controller;
      import org.springframework.beans.factory.annotation.Autowired;
      import org.springframework.util.CollectionUtils;
      import org.springframework.web.bind.annotation.GetMapping;
      import org.springframework.web.bind.annotation.RequestMapping;
      import org.springframework.web.bind.annotation.RestController;
      import per.lmc.tools2.eureka.config.MyNacosProperties;
      import com.lmc.common.enums.LanguageEnum;
      import com.lmc.common.enums.SplitEnum;
      import java.util.HashMap;
      import java.util.List;
      import java.util.Map;
      import java.util.stream.Collectors;
      /**
       * @Description: TODO API返回参数接口
       * @version: 1.0
       */
      @RestController
      @RequestMapping("/apiMessages")
      public class ApiMessageController {
          @Autowired
          private MyNacosProperties myNacosProperties;
          /**
           * 获取所有apiMessages
           * @param language 语言
           * @return 数据集合
           */
          @GetMapping("/getAll")
          public Map<String, String> apiMessages(String language) {
              List<String> apiMessages = myNacosProperties.getApiMessages();
              Map<String, String> result = new HashMap<>(20);
              if (!CollectionUtils.isEmpty(apiMessages)) {
                  if (LanguageEnum.English.value().equalsIgnoreCase(language)) {
                      apiMessages.forEach(a -> result.put(a.split(SplitEnum.API_MESSAGE_SPLIT.value())[0], a.split(SplitEnum.API_MESSAGE_SPLIT.value())[2]));
                  }else {
                      apiMessages.forEach(a -> result.put(a.split(SplitEnum.API_MESSAGE_SPLIT.value())[0], a.split(SplitEnum.API_MESSAGE_SPLIT.value())[1]));
                  }
              }
              return result;
          }
          /**
           * 通过code获取APIMessage
      python     * @param language 语言
           * @param code 参数代码
           * @return 参数代码指定信息
           */
          @GetMapping("/getOne")
          public String getMessage(String language, String code) {
              // 获取指定code的记录
              List<String> apiMessages = myNacosProperties.getApiMessages().stream().filter(a -> a.startsWith(code)).collect(Collectors.toList());
              if (CollectionUtils.isEmpty(apiMessages)) {
                  return String.format("不存在code为%s的记录", code);
              }
              if (LanguageEnum.English.value().equalsIgnoreCase(language)) {
                  return apiMessages.get(0).split(SplitEnum.API_MESSAGE_SPLIT.value())[2];
              }else {
                  return apiMessages.get(0).split(SplitEnum.API_MESSAGE_SPLIT.value())[1];
              }
          }
      }

      2.4.2 MyNacosProperties.java

      package per.lmc.tools2.eureka.config;
      import lombok.Data;
      import org.springframework.boot.context.properties.ConfigurationProperties;
      import org.springframework.cloud.context.config.annotation.RefreshScope;
      import org.springframework.context.annotation.Configuration;
      import java.util.List;
      /**
       * @Description: TODO Nacos配置映射类
       * @version: 1.0
       */
      @Configuration
      @ConfigurationProperties(prefix = "tools")
      @RefreshScope
      @Data
      public class MyNacosProperties {
          List<String> apiMessages;
      }
      

      在nacos中的配置如下所示:

      SpringCloud服务实现同时使用eureka和nacos方法

      2.5 运行测试

      运行服务,访问 http://localhost:9006/eureka-proxy/apiMessages/getAll?language=en,能成功获取到数据

      {"1000":"missing parameter","2000":"server internal exception","0000":"operation succeeded"}

      三,将该服务引入eureka注册中心

      上面服务实际上已经注册到eureka注册中心中,但是,实际上使用中,我们都是通过网关访问的,所以在网关服务的application.yml中,补充下该服务的路由

      server:

       lAwdq; port: 8764

        servlet:

          context-path: /lmc

      spring:

        application:

          name: tools-gateway

        profiles:

          active: dev

        cloud:

          # 消息总线

          bus:

            trace:

              enabled: true

          # 网关配置

          gateway:

            discovery:

      &n编程bsp;       locator:

                enabled: true # 开启根据注册中心路由,并随服务的改变而改变路由

                lower-case-service-id: true # 开启服务名转为小写

      #        globalcors:

      #        default-filters:

      #        - PreserveHostHeader #发送原主机头

            routes:

              - id: tools-task

                uri: lb://tools-task

      #          uri: http://localhost:8083

                predicates:

                  - Path=/tltk/**

              - id: tools-admin

                uri: lb://tools-admin

                predicates:

                  - Path=/monitor/**

                filters:

                  - PreserveHostHeader #发送网关原始主机头

              - id: tools-demo

                uri: lb://tools-demo

                predicates:

                  - Path=/demo/**

              - id: tools-eureka-proxy

                uri: lb://tools-eureka-proxy

                predicates:

                  - Path=/eureka-proxy/**

      eureka:

        client:

          registry-fetch-interval-seconds: 10

        instance:

          instance-id: ${spring.application.name}:${spring.cloud.client.ip-address}:${server.port} # 实例名:application:ip:port

          prefer-ip-address: true # 优先使用IP地址作为主机名的标识

          lease-renewal-interval-in-seconds: 180 # 续约更新时间间隔

          lease-expiration-duration-in-seconds: 200

          #  项目配置有 server.servlet.context-path 属性,想要被 spring boot admin 监控,就要配置以下属性

          health-check-url: http://${spring.cloud.client.ip-address}:${server.port}/actuator/health

      # 暴露监控断点

      management:

        endpoints:

          web:

            exposure:

              include: "*"

            health:

              show-details: always

      logging:

        pattern:

          console: "%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{50} - %msg%n&编程客栈quot;

          file: "%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{50} - %msg%n"

      然后重启网关服务,访问 http://localhost:8764/eureka-proxy/apiMessages/getAll,得到

      {"1000":"缺少参数","2000":"服务器内部异常","0000":"操作成功"}

      因此,eureka成功从nacos获取数据。

      到此这篇关于SpringCloud服务实现同时使用eureka和nacos方法介绍的文章就介绍到这了,更多相关SpringCloud eureka和nacos内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

      0

      上一篇:

      下一篇:

      精彩评论

      暂无评论...
      验证码 换一张
      取 消

      最新开发

      开发排行榜