使用consul注册中心要求服务以自定义instance-id形式注册

推荐博客

使用Consul实现服务发现:instance-id自定义(3种方式)_勇往直前的专栏-CSDN博客 

SpringCloud Consul自定义服务注册_茅坤宝骏氹的博客-CSDN博客

原生java读取apollo配置中心参数_XiuL的博客-CSDN博客_java读取apollo配置

指定服务注册形式

运维要求的指定服务格式如下:

在consul上实际是这样的

 

 

 

 前言

 项目是spring cloud项目,网关使用的gateway,服务间调用使用的feign,注册中心开始使用的eureka,因为要注册到consul,所以最后弃用了eureka,配置中心使用的apollo

依赖

注明:

             网关服务不要添加acuator依赖 

<?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>
    <packaging>pom</packaging>
    <modules>
        <module>business</module>
        <module>commons</module>
        <module>gatewayService</module>
        <module>registryService</module>
        <module>mybatis-generator</module>
    </modules>

    <!--nexus私服 -->
    <repositories>
        <repository>
            <id>nexus-thirdparty</id>
            <name>Nexus ThirdParty Repository</name>
            <url>https://nexus.wsecar.cn/repository/thirdparty/</url>
        </repository>
        <repository>
            <id>nexus-public</id>
            <name>Nexus Public Repository</name>
            <url>https://nexus.wsecar.cn/repository/public/</url>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>nexus-public</id>
            <name>Nexus Public Repository</name>
            <url>https://nexus.wsecar.cn/repository/public/</url>
        </pluginRepository>
    </pluginRepositories>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.14.RELEASE</version>
        <relativePath/>
    </parent>

    <groupId>com.wscar.xny</groupId>
    <artifactId>wscar-xny-parent</artifactId>
    <version>1.0.0</version>
    <description>万顺叫车新能源项目</description>

    <properties>
        <wsBuild.path.jar>/data/wanshun/targetjar</wsBuild.path.jar>
        <wsBuild.path.zip>/data/wanshun/targetzip</wsBuild.path.zip>

        <java.source.version>1.8</java.source.version>
        <java.target.version>1.8</java.target.version>
        <maven.compiler.plugin.version>3.5.1</maven.compiler.plugin.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

        <java.version>1.8</java.version>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>

        <json-lib.version>2.4</json-lib.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <spring-cloud.version>Greenwich.SR5</spring-cloud.version>
        <spring-boot.version>2.1.14.RELEASE</spring-boot.version>
        <tk.mybatis.version>2.1.5</tk.mybatis.version>
        <reids-starter-version>2.2.5.RELEASE</reids-starter-version>
        <pagehelper.version>1.2.12</pagehelper.version>
        <qcloudsms.version>1.0.6</qcloudsms.version>
        <tencent.cos.version>3.0.6</tencent.cos.version>
        <tencent.qcloud.version>5.6.22</tencent.qcloud.version>
        <apollo.version>0.11.0</apollo.version>
        <druid.version>1.1.22</druid.version>
        <aliyun-java-sdk-core.version>4.0.3</aliyun-java-sdk-core.version>
        <lombok.maven.plugin.version>1.18.12.0</lombok.maven.plugin.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok-maven-plugin</artifactId>
            <version>${lombok.maven.plugin.version}</version>
        </dependency>

        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>${pagehelper.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-log4j2</artifactId>
        </dependency>
        <!--        <dependency>-->
        <!--            <groupId>org.springframework.cloud</groupId>-->
        <!--            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>-->
        <!--        </dependency>-->

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

        <!--Prometheus配置-->
        <dependency>
            <groupId>io.micrometer</groupId>
            <artifactId>micrometer-registry-prometheus</artifactId>
            <version>1.1.3</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-consul-discovery</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

        <!-- redis -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
            <version>${reids-starter-version}</version>
            <exclusions>
                <exclusion>
                    <groupId>io.lettuce</groupId>
                    <artifactId>lettuce-core</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.58</version>
        </dependency>

        <dependency>
            <groupId>io.github.openfeign</groupId>
            <artifactId>feign-httpclient</artifactId>
        </dependency>
    
                <!-- 会引起缓存序列化问题,热部署对修改方法签名无效,没啥卵用,排除掉 -->
                <exclusions>
                    <exclusion>
                        <groupId>org.springframework.boot</groupId>
                        <artifactId>spring-boot-devtools</artifactId>
                    </exclusion>
                </exclusions>
            </dependency>

            <dependency>
                <groupId>tk.mybatis</groupId>
                <artifactId>mapper-spring-boot-starter</artifactId>
                <version>${tk.mybatis.version}</version>
            </dependency>

            <dependency>
                <groupId>com.github.qcloudsms</groupId>
                <artifactId>qcloudsms</artifactId>
                <version>${qcloudsms.version}</version>
            </dependency>

            <dependency>
                <groupId>com.tencent.cloud</groupId>
                <artifactId>cos-sts-java</artifactId>
                <version>${tencent.cos.version}</version>
            </dependency>

            <dependency>
                <groupId>com.qcloud</groupId>
                <artifactId>cos_api</artifactId>
                <version>${tencent.qcloud.version}</version>
                <exclusions>
                    <exclusion>
                        <groupId>commons-codec</groupId>
                        <artifactId>commons-codec</artifactId>
                    </exclusion>
                </exclusions>
            </dependency>

            <dependency>
                <groupId>com.ctrip.framework.apollo</groupId>
                <artifactId>apollo-client</artifactId>
                <version>${apollo.version}</version>
            </dependency>

            <dependency>
                <groupId>com.ctrip.framework.apollo</groupId>
                <artifactId>apollo-core</artifactId>
                <version>${apollo.version}</version>
            </dependency>

            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid-spring-boot-starter</artifactId>
                <version>${druid.version}</version>
            </dependency>

            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>${mysql.version}</version>
            </dependency>

            <dependency>
                <groupId>com.aliyun</groupId>
                <artifactId>aliyun-java-sdk-core</artifactId>
                <version>${aliyun-java-sdk-core.version}</version>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*</include>
                </includes>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                    <include>**/*.properties</include>
                </includes>
            </resource>
        </resources>

        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>${maven.compiler.plugin.version}</version>
                <configuration>
                    <source>${java.source.version}</source>
                    <target>${java.target.version}</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

自定义instan-id等配置文件

package com.wscar.xny.gateway.config;


import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.ConfigService;
import com.ecwid.consul.v1.ConsulClient;
import com.ecwid.consul.v1.agent.model.NewService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.consul.discovery.ConsulDiscoveryProperties;
import org.springframework.cloud.consul.discovery.HeartbeatProperties;
import org.springframework.cloud.consul.discovery.TtlScheduler;
import org.springframework.cloud.consul.serviceregistry.ConsulRegistration;
import org.springframework.cloud.consul.serviceregistry.ConsulServiceRegistry;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class CousulRegistryConfig extends ConsulServiceRegistry {

    private ConsulDiscoveryProperties properties;
    private ConsulClient consulClient;

    @Autowired
    private Environment environment;


    public CousulRegistryConfig(ConsulClient client, ConsulDiscoveryProperties properties, @Autowired(required = false) TtlScheduler ttlScheduler, HeartbeatProperties heartbeatProperties) {
        super(client, properties, ttlScheduler, heartbeatProperties);
        this.properties = properties;
        this.consulClient = client;

    }

    public void register(ConsulRegistration reg) {

        String ipAddress = properties.getIpAddress();  //ip地址
        String hostname = properties.getHostname(); //主机名称
        Config parent = ConfigService.getConfig("wsGreenCar.zk");
        String envType = parent.getProperty("app.env", ""); //从apollo配置中心中拿到当前的环境(dev/test/uat/prod)

        String serverName = environment.getProperty("spring.application.name");  //当前服务名称
        NewService service = reg.getService();   //拿到默认的服务注册信息的service信息
        service.setAddress(properties.getIpAddress());
        service.setPort(reg.getPort());
        ArrayList<String> list = new ArrayList<>();
        list.add(envType);
        service.setTags(list);
        service.setName(envType + "-" + "wsXinnengyuan" + "-" + serverName);

        Map<String, String> map = new HashMap<>();
        map.put("project", "wsXinnengyuan");
        map.put("category", "wsXinnengyuan-" + service.getName());
        map.put("exporter", "wsXinnengyuan-exports");
        map.put("hostname", hostname);
        map.put("appname", serverName);
        map.put("metric", "/actuator/prometheus");
        service.setMeta(map);   //自定义service的Meta信息

        NewService.Check check = new NewService.Check();    //自定义consul的自我检查机制
        check.setHttp(String.format("%s://%s:%s%s", properties.getScheme(), properties.getIpAddress(), reg.getPort(), "/actuator/health"));
        check.setInterval("10s");   //检查的间隔时间设置10s
        service.setCheck(check);


        service.setMeta(map);
        service.setId(envType + "-" + "wsXinnengyuan" + "-" + serverName + "-" + ipAddress);           //自定义instance-id
        super.register(reg);   //consul开始服务注册
    }

}

 springBoot启动类重写ConsulClient,从 apollo配置中心中拿到consul的注册中心地址

package com.wscar.xny.gateway;

import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.ConfigService;
import com.ctrip.framework.apollo.spring.annotation.EnableApolloConfig;
import com.ecwid.consul.v1.ConsulClient;
import io.micrometer.core.instrument.MeterRegistry;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.actuate.autoconfigure.metrics.MeterRegistryCustomizer;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;

/**
 * Created by 赵继 on 2020/5/19.
 */
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
@ComponentScan(basePackages = {"com.wscar.xny"})
@EnableFeignClients          //开启服务间调用feign
//@EnableEurekaClient
@EnableDiscoveryClient             //开启consul服务注册
@EnableApolloConfig             //开启配置中心apollo配置
public class GatewayApplication {
    public static void main(String[] args) {
        SpringApplication.run(GatewayApplication.class, args);
    }

//prometheus监控
    @Bean
    MeterRegistryCustomizer<MeterRegistry> configurer(
            @Value("${spring.application.name}") String applicationName) {
        return (registry) -> registry.config().commonTags("application", applicationName);
    }

//重新注入Bean==ConsulClient
    @Bean
    public ConsulClient consulClient() {
        //从apollo配置中拿到consul注册中心的地址
        Config parent = ConfigService.getConfig("wsGreenCar.zk");
        String metrisAddress = parent.getProperty("consul.metricAddress", "");
        String s = metrisAddress.substring(0, metrisAddress.lastIndexOf(":"));
        return new ConsulClient(s);
    }
}

 apollo配置中心中的配置

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值