@SpringBootApplication
@EnableEurekaServer
public class RegistryApplication {
public static void main(String[] args) {
SpringApplication.run(RegistryApplication.class);
}
}
3、main方法启动,通过网页:localhost:8080启动查看
三、向注册中心注册(提供)服务
1、配置application.yml文件(该文件实在resources下面)
# HTTP (Tomcat) port
server:
port: 8081
#Application name
spring:
application:
name: micro-service
# Discovery Server Access
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8080/eureka/
2、基于RESTful风格编写一个服务并暴露
@RestController
public class HelloWorldController {
@RequestMapping("hello/{name}")
public String hello(@PathVariable String name) {
return name + " say hello";
}
}
3、编写启动程序
@SpringBootApplication
@EnableDiscoveryClient
public class ServiceApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceApplication.class, args);
}
}
4、启动成功
5、网页刷新http://localhost:8080
此时我们就会发现服务已经注册到了注册中心
四 micro-client端发现(调用)服务
1、配置文件application.yml
# HTTP (Tomcat) port
server:
port: 8082
#Application name
spring:
application:
name: micro-client
# Discovery Server Access
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8080/eureka/
# application parameters
app:
service-url: http://MICRO-SERVICE/
2、编写 Controller层
@RestController
public class CallHelloController {
@Autowired
private CallHelloService callHelloService;
@GetMapping("hello")
public String hello(String name) {
String result = callHelloService.callHello(name);
return result;
}
}
3、编写service层,通过service来调用服务
@Service
public class CallHelloService {
@Value("${app.service-url}")
private String appServiceUrl;
@Autowired
private RestTemplate restTemplate;
public String callHello(String name) {
// 是一个http client
ResponseEntity
result = restTemplate.postForEntity(appServiceUrl + "hello/" + name, null, String.class);
return result.getBody();
}
}