springcloud-1.使用Eureka -robbon构建自动服务发现注册集群和消费者

1.使用Eureka组件创建服务中心Server_1

@EnableEurekaServer  //表示自己是一个server
@SpringBootApplication
public class EurekaserverApplication {

    public static void main(String[] args) {
        SpringApplication.run(EurekaserverApplication.class, args);
    }
}
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/
server:
  port: 8764
spring:
  application:
    name: service-ribbon

通过eureka.client.registerWithEureka:false和fetchRegistry:false来表明自己是一个eureka server.



2.使用Eureka组件创建客服端Clinet_P_1,Clinet_P_2,即P表示生产者,服务提供者。并且指定服务中心的地址Server_1。

@SpringBootApplication
@EnableEurekaClient   //表示自己是一个client
@RestController
public class ServiceHiApplication {

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

    @Value("${server.port}")
    String port;
    @RequestMapping("/hi")
    public String home(@RequestParam String name) {
        return "hi "+name+",i am from port:" +port;
    }

}


3.使用ribbon组件创建客户端Client_C_1,C表示customer,服务消费者,并且指定服务中心的地址Server_1。

创建主类
@SpringBootApplication
@EnableDiscoveryClient
public class ServiceRibbonApplication {

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

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

}

调用远程服务

@Service
public class HelloService {

    @Autowired
    RestTemplate restTemplate;

    public String hiService(String name) {
        return restTemplate.getForObject("http://SERVICE-HI/hi?name="+name,String.class);
    }

}

配置文件

eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/
server:
  port: 8764
spring:
  application:
    name: service-ribbon


参考: http://blog.csdn.net/forezp/article/details/69788938

        http://blog.csdn.net/forezp/article/details/69696915

猜你喜欢

转载自blog.csdn.net/xtj332/article/details/79415059
今日推荐