![](https://img.haomeiwen.com/i9533696/c78d919b9f8a0ae8.png)
要写controller,那么就要引入spring的web组件
pom的name能够打印出更友好的信息?
1. 创建入口类EurekaClientApplication
创建springBoot启动类
启动方式是webapplication中的servlet类型
启用EnableDiscoveryClient发现服务(到服务中心拉取服务注册列表)
package com.imooc.springcloud;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@SpringBootApplication
@EnableDiscoveryClient
public class EurekaClientApplication {
public static void main(String[] args) {
new SpringApplicationBuilder(EurekaClientApplication.class)
.web(WebApplicationType.SERVLET)
.run(args);
}
}
2. 创建Controller对外提供service
- 创建Controller
@Slf4j简写代码
@Value("${server.port}"),说明元素从哪里来
创建对外提供的方法sayHi() - 创建entity Friend
lombok使用?
Controller
package com.imooc.springcloud;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
@Slf4j
public class Controller {
@Value("${server.port}")
private String port;
@GetMapping("/sayHi")
public String sayHi(){
return "This is "+ port;
}
@PostMapping("/sayHi")
public Friend sayHiPost(@RequestBody Friend friend){
log.info("You are"+friend.getName());
friend.setPort(port);
return friend;
}
}
entity Friend
package com.imooc.springcloud;
import lombok.Data;
@Data
public class Friend {
private String name;
private String port;
}
3. application.properties
- 创建application.properties
- 启动如果client的ip地址有问题?重启服务即可
spring.application.name=eureka-client
server.port=30002
eureka.client.serviceUrl.defaultZone=http://127.0.0.1:20000/eureka/
#eureka.client.serviceUrl.defaultZone=http://peer2:20000/eureka/,http://peer1:20001/eureka/
# 每隔5秒钟,向服务中心发送一条续约指令
#eureka.instance.lease-renewal-interval-in-seconds=5
# 如果30秒内,依然没有收到续约请求,判定服务过期(上西天)
#eureka.instance.lease-expiration-duration-in-seconds=30
4.实现效果?
启动eureka-server及eureka-client
访问http://127.0.0.1:20000/
![](https://img.haomeiwen.com/i9533696/bc65492d34c555e0.png)
网友评论