1 第一步spring
1)建立eureka服務中心 //至關於dubbo使用zookeeper的原理app
pom.xmlide
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId> </dependency>
eureka.client.service-url.defaultZone= http://localhost:8761/eureka/測試
server.port=8001fetch
eureka.instance.hostname=eureka-serverurl
eureka.client.register-with-eureka=false.net
eureka.client.fetch-registry=falserest
3)在主應用中啓用eureka @EnableEurekaServercode
測試結果server
2 建立服務提供者的應用
1)pom.xml
<dependency>
<groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency>
server.port=8002
spring.application.name=provider
#使用服務的ip地址來進行註冊
eureka.instance.prefer-ip-address=true
eureka.client.service-url.defaultZone:http://127.0.0.1:8761/eureka/
4)建立向外提供服務的controller @RestController
public class BookController {
@Autowired BookService bookService; @GetMapping("/book")
public String getBook(){
return bookService.getBook();
} }
3 建立消費者
1)pom.xml
<dependency>
<groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency>
spring.application.name=consumer
server.port=8200
eureka.instance.prefer-ip-address=true
eureka.client.service-url.defaultZone:http://localhost:8761/eureka/
3)編寫調用服務的controller
@RestController
public class helloController {
@Autowired RestTemplate restTemplate; @GetMapping("/hello")
public String UserBook(String name){
String s= restTemplate.getForObject("http://PROVIDER/book",String.class); return name+"購買了"+s;
} }
4)啓用從遠程調用服務 @EnableDiscoveryClient
@SpringBootApplication
public class ConsumerApplication {
public static void main(String[] args) { SpringApplication.run(ConsumerApplication.class, args); } @Bean @LoadBalanced public RestTemplate restTemplate(){
return new RestTemplate();
} }
測試結果: