Spring Cloud ( openFeign 服务发现、配置、公共client抽取 )
以下是使用Spring Cloud和OpenFeign进行服务发现、配置管理和公共client抽取的示例代码:
- 公共client抽取(
CommonClient.java
):
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
@FeignClient(name = "service-provider", url = "${service-provider.url}")
public interface CommonClient {
@GetMapping("/greeting")
String greeting();
}
- 服务提供者(
ServiceProviderController.java
):
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ServiceProviderController {
@Value("${greeting.message:Hello from service-provider}")
private String greetingMessage;
@GetMapping("/greeting")
public String greeting() {
return greetingMessage;
}
}
- 服务消费者(
ConsumerApplication.java
和ConsumerController.java
):
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
@EnableFeignClients
@EnableDiscoveryClient
@SpringBootApplication
public class ConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(ConsumerApplication.class, args);
}
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ConsumerController {
@Autowired
private CommonClient commonClient;
@GetMapping("/consumer/greeting")
public String greeting() {
return commonClient.greeting();
}
}
application.yml
配置(服务提供者和消费者):
spring:
application:
name: service-provider
---
spring:
application:
name: service-consumer
cloud:
config:
uri: http://config-server
discovery:
enabled: true
service-id: config-server
bootstrap.yml
配置:
spring:
cloud:
config:
profile: ${spring.profiles.active}
label: mast
评论已关闭