请参考 : SpringCloud H系列 alibaba 2.1.1 (一) nacos1.X 注册中心 服务端
pom.xml 工程文件
com.alibaba
spring-cloud-hoxton
1.0
alibaba-nacos-discovery-client
1.0
jar
org.springframework.boot
spring-boot-starter-webflux
org.springframework.boot
spring-boot-starter-web
org.springframework.cloud
spring-cloud-starter-openfeign
com.alibaba.cloud
spring-cloud-starter-alibaba-nacos-discovery
application.yml 配置文件
server:
port: 9000
spring:
application:
name: alibaba-nacos-discovery-client-webclient
cloud:
nacos:
discovery:
server-addr: 192.168.1.141:8848
TestApplication.java 启动类
@EnableDiscoveryClient //启动注册中心客户端 注册到nacos
@SpringBootApplication
@EnableFeignClients //开启Feign客户端
public class TestApplication {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
}
客户端需要根据服务名请求服务端的接口
CommonController.java 服务端接口调用
@Slf4j
@RestController
public class CommonController {
@Autowired
LoadBalancerClient loadBalancerClient;
@GetMapping("/testCommon")
public String test() {
ServiceInstance serviceInstance = loadBalancerClient.choose("alibaba-nacos-discovery-server");
String url = serviceInstance.getUri() + "/test?name=common";
RestTemplate restTemplate = new RestTemplate();
String result = restTemplate.getForObject(url, String.class);
return "返回数据 : " + result;
}
}
测试
成功
WebFluxConfig.java 配置类
@Configuration
public class WebFluxConfig {
@Bean
@LoadBalanced
public WebClient.Builder loadBalancedWebClientBuilder() {
return WebClient.builder();
}
}
WebFluxController.java 服务端接口调用
@Slf4j
@RestController
public class WebFluxController {
@Autowired
private WebClient.Builder webClientBuilder;
@GetMapping("/testWebFlux")
public Mono test() {
Mono result = webClientBuilder.build().get()
.uri("http://alibaba-nacos-discovery-server/test?name=webFlux")
.retrieve().bodyToMono(String.class);
return result;
}
}
测试
成功
RestTemplateConfig.java 配置类
@Configuration
public class RestTemplateConfig {
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
RestTemplateController.java 服务端接口调用
@Slf4j
@RestController
public class RestTemplateController {
@Autowired
private RestTemplate restTemplate;
@GetMapping("/testRest")
public String test() {
String result = restTemplate.getForObject("http://alibaba-nacos-discovery-server/test?name=restTemplate", String.class);
return "返回数据 : " + result;
}
}
测试
成功
TestServiceFeign.java 调用服务端的接口
@FeignClient("alibaba-nacos-discovery-server")
public interface TestServiceFeign {
@GetMapping("/test")
String hello(@RequestParam(name = "name") String name);
}
FeginController.java 调用配置好的接口
@Slf4j
@RestController
public class FeignController {
@Autowired
private TestServiceFeign client;
@GetMapping("/testFeign")
public String test() {
String result = client.hello("feign");
return "返回数据 : " + result;
}
}
测试
成功
项目已上传到gitee
地址: spring-cloud-alibaba-H-demo
如果帮到您了,请帮忙点个star