springcloud-1.使用Eureka -robbon構建自動服務發現註冊叢集和消費者
阿新 • • 發佈:2018-10-31
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