SpringCloud之Eureka服务注册中心,服务注册和服务发现

我使用的版本

springboot版本
<version>1.5.14.RELEASE</version>
 springcloud版本
<spring-cloud.version>Edgware.SR4</spring-cloud.version>

使用eureka写一个注册中心,相当于zookeeper的地位
引入eurekaServer 的依赖

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

配置eurekaServer

server:
  port: 8761
eureka:
  instance:
    hostname: eureka-server
  client:
    register-with-eureka: false
    fetch-registry: false
    service-url:
      defaultZone: http://localhost:8761/eureka/  #默认配置

@EnableEurekaServer,启动eurekaServer


@EnableEurekaServer
@SpringBootApplication
public class Server3Application {

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

访问http://localhost:8761/ 出现eurekaServer注册中心的界面

写provider,多复制几个,改一下端口号


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

server:
  port: 8001
spring:
  application:
    name: provider-ticket
eureka:
  instance:
    prefer-ip-address: true # 注册服务的时候使用服务的ip地址
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/

使用RestAPI提供服务

@RestController
public class UserController {

    @GetMapping("/ticket")
    public String test(){
        System.out.println("===================>8001");
        return "8001 provider";
    }
}

写一个消费者
引入依赖

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

配置消费者


spring:
  application:
    name: consumer-user
server:
  port: 8100
eureka:
  instance:
    prefer-ip-address: true # 注册服务的时候使用服务的ip地址
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/

发现服务@EnableDiscoveryClient
配置一个RestTemplate,并启动负债均衡@LoadBalanced
启动消费者

@EnableDiscoveryClient
@SpringBootApplication
public class ConsumerApplication {

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


    @LoadBalanced
    @Bean
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
}

访问该consumer自动远程调用provider

@RestController
public class UserController {

    @Autowired
    RestTemplate restTemplate;

    @GetMapping("/buy")
    public String test() {
        System.out.println("===========================>8100");
        String forObject = restTemplate.getForObject("http://PROVIDER-TICKET/ticket", String.class);
        System.out.println(forObject);
        return forObject;
    }

}

访问localhost://8761可以看到注册中心中有两个服务提供者和一个服务消费者
这里写图片描述

访问http://localhost:8100/buy
会发现界面轮流出现8001 provider,8002 provider,启动了负债均衡

猜你喜欢

转载自blog.csdn.net/lhc0512/article/details/81109158
今日推荐