之前初步认识了服务器和客户端的配置,这里记录一下服务调用者(server-invoker)与服务提供者(server-provider)的调用,而这两者都属于客户端,所以都需要在启动类加@EnableEurekaClient注解
@SpringBootApplication
@EnableEurekaClient
public class EurekaInvokerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaInvokerApplication.class, args);
}
}
然后将两个客户端都注册到服务器,为服务提供者(server-provider)命名eureka-provider;服务调用者(server-invoker)命名server-invoker,端口号为9000
#server-provider
spring:
application:
name: server-provider
eureka:
instance:
hostname: localhost
client:
service-url:
defaultZone: http://localhost:8761/eureka/
#server-invoker
server:
port: 9000
spring:
application:
name: server-invoker
eureka:
instance:
hostname: localhost
client:
service-url:
defaultZone: http://localhost:8761/eureka/
在服务提供者(server-provider)中写一个Person类和一个MainController类,MainController用了@RestController注解,方便页面显示
public class Person {
private Integer id;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Person(Integer id, String name) {
this.id = id;
this.name = name;
}
public Person() {
}
}
@RestController
public class MainController {
@GetMapping("/person/{id}")
public Person findPerson(@PathVariable("id") Integer id) {
Person person = new Person(id, "test");
return person;
}
}
现在在服务调用者(server-invoker)中写一个MainController类,为了方便,将配置类、也写到MainController类中,详细看注释
@Configuration
@RestController
public class MainController {
@Bean
@LoadBalanced // 使用@LoadBalanced注解后,这个RestTemplate实例就能访问分布式服务
public RestTemplate getRestTemplate() {
return new RestTemplate();
}
@GetMapping("/router")
public String router() {
RestTemplate restTpl = getRestTemplate();
// 这里的server-provider与之前配置的spring。application.name = server-invoker对应
String json = restTpl.getForObject("http://server-provider/person/1", String.class);
return json;
}
}
最后访问http://localhost:9000/router就能通过服务调用者访问服务提供者了。