zoukankan      html  css  js  c++  java
  • 服务注册与发现

    服务发现模块:Eureka

    创建服务注册中心

    pom依赖

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-eureka-server</artifactId>
    </dependency>

    通过@EnableEurekaServer注解启动一个服务注册中心提供给其他应用进行对话,只需要在一个普通的Spring Boot应用中添加这个注解就能开启此功能.

    @EnableEurekaServer
    @SpringBootApplication
    public class Application {
        public static void main(String[] args) {
            new SpringApplicationBuilder(Application.class).web(true).run(args);
        }
    }

      

    在默认设置下,该服务注册中心也会将自己作为客户端来尝试注册它自己,所以我们需要禁用它的客户端注册行为,只需要在application.properties中增加如下配置  

    #spring boot port
    server.port=1111
    
    #禁用它的客户端注册行为
    eureka.client.register-with-eureka=false
    eureka.client.fetch-registry=false
    
    #注册中心地址
    eureka.client.serviceUrl.defaultZone=http://localhost:${server.port}/eureka/

    创建服务提供方

    pom依赖

    <dependency>
            <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-eureka</artifactId>
    </dependency>

    通过DiscoveryClient对象,在日志中打印出服务实例的相关内容。

    @RestController
    public class ComputeController {
        private final Logger logger = Logger.getLogger(getClass());
        
    @Autowired
    private DiscoveryClient client;
    @RequestMapping(value
    = "/add" ,method = RequestMethod.GET) public Integer add(@RequestParam Integer a, @RequestParam Integer b) { ServiceInstance instance = client.getLocalServiceInstance(); Integer r = a + b; logger.info("/add, host:" + instance.getHost() + ", service_id:" + instance.getServiceId() + ", result:" + r); return r; } }

      

    主类中通过加上@EnableDiscoveryClient注解,该注解能激活Eureka中的DiscoveryClient实现,才能实现Controller中对服务信息的输出

    @EnableDiscoveryClient
    @SpringBootApplication
    public class ComputeServiceApplication {
        public static void main(String[] args) {
            new SpringApplicationBuilder(ComputeServiceApplication.class).web(true).run(args);
        }
    }

     application.properties 配置

    #服务实例名
    spring.application.name=compute-service
    
    #spring boot port
    server.port=2222
    
    #注册中心地址,多个值以逗号隔开
    eureka.client.serviceUrl.defaultZone=http://localhost:1111/eureka/
  • 相关阅读:
    用于视频行为识别的双流卷积网络
    python更改默认版本
    ubuntu16安装ROS(包括win10子系统ubuntu同样能用)
    js中的new做了什么?
    Promise是什么?
    滚动轴 scroll
    什么是ES6?
    什么是token及怎样生成token
    mongodb 删库跑路
    css如何设置背景图片?background属性添加背景图片
  • 原文地址:https://www.cnblogs.com/zhangjianbin/p/6262002.html
Copyright © 2011-2022 走看看