Spring Cloud - 服务发现、注册、调用(二)

Spring Cloud - 服务发现、注册、调用

  • Spring Cloud - 服务发现、注册、调用(一)(eureka server)
  • Spring Cloud - 服务发现、注册、调用(二)(eureka client(provider))
  • Spring Cloud - 服务发现、注册、调用(三)(eureka client(consumer))

代码参见https://github.com/happut/springbootdemo

eureka client (provider)

既然有了服务注册的服务器,那么咱们就可以进行服务注册了,实际上服务注册服务器相当于一个中介,提供者将服务提供到注册服务器中,消费者只需要跟注册服务器打交道,不用硬编码具体的某个提供者。

建立springboot项目,增加spring-cloud-starter-eureka-server起步依赖:



    4.0.0

    com.github.happut
    springboot-demo-eureka-server
    0.0.1-SNAPSHOT
    jar

    springboot-demo-eureka-server
    Demo project for Spring Boot

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

    
        UTF-8
        UTF-8
        1.8
        Edgware.RELEASE
    

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

        
            org.springframework.boot
            spring-boot-devtools
            runtime
        
        
            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
            
        
    




启动代码中增加@EnableEurekaClient

@SpringBootApplication
@EnableEurekaClient
public class SpringbootDemoEurekaProviderApplication {

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

application.properties(yml请注意缩进)

server.port=1112

spring.application.name=hello-service-provider

eureka.client.serviceUrl.defaultZone=http://localhost:1111/eureka

这里需要注意下端口不要和主服务器冲突,否则无法启动。

spring.application.name代表服务名称,前面说到,消费者无需硬编码接口服务器的ip、端口等,而需要依赖服务名称,这个等到搭建服务消费者的时候会提到。

eureka.client.serviceUrl.defaultZone务必要和主服务器一致,否则你也注册不上去啊。

在这里为了演示,我们临时写一个接口:

@RestController
public class HelloController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());


    @RequestMapping("/hello")
    public String index() {
        return "ok";
    }
}

然后乐呵启动,我们可以简单测试下接口:


Spring Cloud - 服务发现、注册、调用(二)_第1张图片
image.png

顺便看下主服务器中的变化:


Spring Cloud - 服务发现、注册、调用(二)_第2张图片
image.png

可以看到我们的服务,已经被主服务器发现了。
服务名称就是刚才我们在application.properties中的设置

你可能感兴趣的:(Spring Cloud - 服务发现、注册、调用(二))