Spring Eureka 服务注册 发现

Idea创建项目


image.png

image.png

image.png

POM依赖



    4.0.0

    com.example
    demo
    0.0.1-SNAPSHOT
    jar

    demo
    Demo project for Spring Boot

    
        org.springframework.boot
        spring-boot-starter-parent
        1.5.9.RELEASE
         
    

    
        UTF-8
        UTF-8
        1.8
        Edgware.SR1
    

    
        
            org.springframework.cloud
            spring-cloud-starter-eureka-server
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
        
    

    
        
            
                org.springframework.cloud
                spring-cloud-dependencies
                ${spring-cloud.version}
                pom
                import
            
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    




yml配置文件

//端口号
server:
  port: 8081
//不将自身注册为client
eureka:
  instance:
    hostname: localhost
  client:
    register-with-eureka: false
    fetch-registry: false
    service-url:
       defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/

定义入口

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

@EnableEurekaServer --启用服务注册服务器
@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

运行项目以后 启动 输入 localhost:8081


image.png

显示(No instances available) 没有可用的实例

下来配置服务注册客户端
新建项目步骤 同上
yml配置

//配置服务注册地址
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/
server:
  port: 8083
spring:
  application:
    name: Client

启用客户端注册

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@EnableEurekaClient --客户端
@SpringBootApplication
@RestController
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
    @GetMapping("/home")
    public  String home(@RequestParam String name){
        return "姓名:"+name;
    }
}

运行项目 注册的实例


image.png

服务端地址 https://github.com/596442958/Spring-Boot-Eureka-Server
客户端地址 https://github.com/596442958/Spring-Boot-Eureka-Client
官方文档地址 https://springcloud.cc/spring-cloud-dalston.html#_service_discovery_eureka_clients

你可能感兴趣的:(Spring Eureka 服务注册 发现)