SpringCloud 三種服務調用方式
本文主要介紹 SpringCloud 中調用服務的方式:
-
Spring DiscoveryClient
-
支持 Ribbon 的 RestTemplate
-
Feign 客戶端
服務測試環境
測試中,發現 Netflix 的 Eureka 服務層採用。
主要步驟如下:
1. 引入 Eureka 所需的依賴
<!--eureka服務端-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka-server</artifactId>
</dependency>
<!--客戶端-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
2. 修改配置文件
服務端:
eureka:
instance:
hostname: eureka9001.com #eureka服務端的實例名稱
instance-id: eureka9001
client:
register-with-eureka: false #false表示不向註冊中心註冊自己
fetch-registry: false # #false 表示自己就是註冊中心,職責就是維護服務實例,並不需要去檢索服務
service-url:
defaulteZone: http://127.0.0.1:9001
客戶端 1:
server:
port: 8002
spring:
application:
name: licensingservice
eureka:
instance:
instance-id: licensing-service-8002
prefer-ip-address: true
client:
register-with-eureka: true
fetch-registry: true
service-url:
defaultZone: http://127.0.0.1:9001/eureka/,
客戶端 2:
server:
port: 8002
spring:
application:
name: licensingservice
eureka:
instance:
instance-id: licensing-service-8002
prefer-ip-address: true
client:
register-with-eureka: true
fetch-registry: true
service-url:
defaultZone: http://127.0.0.1:9001/eureka/,
一組微服務的不同實例採辦服務名稱不同,不同的實例 ID 不同,不同,spring.application.name
和eureka.instance.instance-id
。
3. 啓動服務
服務端:
@SpringBootApplication
@EnableEurekaServer
public class EurekaServerPort9001_App {
public static void main(String[] args) {
SpringApplication.run(EurekaServerPort9001_App.class,args);
}
}
客戶端:
@SpringBootApplication
@RefreshScope
@EnableEurekaClient
public class LicenseApplication_8002 {
public static void main(String[] args) {
SpringApplication.run(LicenseApplication_8002.class, args);
}
}
4. 測試
進入到 Eureka 服務端地址,我這是127.0.0.1:9001
,可以查看註冊到註冊中心的服務。
標籤:
注意:Eureka 通過兩次服務檢測均到通過,服務將在間隔 10 秒內成功啓動服務註冊等待 30 秒。
消費者
1. 發現客戶端方式
服務中既是服務是微信也可以是調用者,消費者配置和上面配置的大體參考一致,依賴及配置服務端啓動方式EnableEurekaClient
:監聽啓動。
@SpringBootApplication
@EnableEurekaClient
@EnableDiscoveryClient
public class ConsumerApplication_7002 {
public static void main(String[] args) {
SpringApplication.run(ConsumerApplication_7002.class, args);
}
}
核心配置類:
@Component
public class ConsumerDiscoveryClient {
@Autowired
private DiscoveryClient discoveryClient;
public ServiceInstance getServiceInstance() {
List<ServiceInstance> serviceInstances = discoveryClient.getInstances("licensingservice");
if (serviceInstances.size() == 0) {
return null;
}
return serviceInstances.get(0);
}
public String getUrl(String url) {
ServiceInstance serviceInstance=this.getServiceInstance();
if (serviceInstance==null)
throw new RuntimeException("404 ,NOT FOUND");
String urlR=String.format(url,serviceInstance.getUri().toString());
return urlR;
}
}
通過DiscoveryClient
從尤里卡中獲取licensingservice
服務的實例,並返回第一個實例。
測試控制器
@RestController
@RequestMapping("test")
public class TestController {
//注意必須new,否則會被ribbon攔截器攔截,改變URL行爲
private RestTemplate restTemplate=new RestTemplate();
@Autowired
private ConsumerDiscoveryClient consumerDiscoveryClient;
@RequestMapping("/getAllEmp")
public List<Emp> getAllLicense(){
String url=consumerDiscoveryClient.getUrl("%s/test/getAllEmp");
return restTemplate.getForObject(url,List.class);
}
}
測試:
- 調試信息
licensingservice
,擁有兩個服務實例,並可以查看實例信息。
- 頁面返回信息
成功查詢到數據庫存儲信息。
2.Ribbon 方式功能的 Spring RestTemplate
同上。
核心配置類:
//指明負載均衡算法
@Bean
public IRule iRule() {
return new RoundRobinRule();
}
@Bean
@LoadBalanced //告訴Spring創建一個支持Ribbon負載均衡的RestTemplate
public RestTemplate restTemplate() {
return new RestTemplate();
}
設置均衡方式爲輪詢方式。
測試類:
@RestController
@RequestMapping("rest")
public class ConsumerRestController {
@Autowired
private RestTemplate restTemplate;
private final static String SERVICE_URL_PREFIX = "http://LICENSINGSERVICE";
@RequestMapping("/getById")
public Emp getById(Long id) {
MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<String, Object>();
paramMap.add("id", id);
return restTemplate.postForObject(SERVICE_URL_PREFIX + "/test/getById", paramMap, Emp.class);
}
}
測試結果:
第一次:
第二次:
第三次:
因爲採用輪詢平均方式分別使用不同的服務實例,未區別,將名稱確定了一定的。
這上面,Ribbon 是對第一種方式的封裝方式和不同的負載率。 Feign 的方式則大大降低了開發客戶端和提升速度。
3.feign 客戶端方式
引入依賴:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
主要代碼:
@FeignClient(value = "LICENSINGSERVICE",fallbackFactory = ServiceImp.class)
public interface ServiceInterface {
@RequestMapping("/test/getById")
Emp getById(@RequestParam("id") Long id);
@RequestMapping("/test/getLicenseById")
License getLicenseById(@RequestParam("id") Long id);
@RequestMapping("/test/getAllEmp")
List<Emp> getAllLicense();
}
@Component
public class ServiceImp implements FallbackFactory<ServiceInterface> {
@Override
public ServiceInterface create(Throwable throwable) {
return new ServiceInterface() {
@Override
public Emp getById(Long id) {
Emp emp = new Emp();
emp.setName("i am feign fallback create");
return emp;
}
@Override
public License getLicenseById(Long id) {
return null;
}
@Override
public List<Emp> getAllLicense() {
return null;
}
};
}
}
注採用接口模式,通過指定服務名以及方法,在服務開發結果不佳時,方便返回默認的,而不是一個不友好的錯誤。
主啓動類:
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
public class Consumer_feign_Application_7004 {
public static void main(String[] args) {
SpringApplication.run(Consumer_feign_Application_7004.class, args);
}
}
測試類:
@RestController
@RequestMapping("rest")
public class ConsumerRestController {
@Autowired
private ServiceInterface serviceInterface;
@Autowired
private RestTemplate restTemplate;
@RequestMapping("/getById")
public Emp getById(Long id) {
return serviceInterface.getById(id);
}
}
測試結果:
正常測試:
關閉兩個服務實例,模擬服務實例死亡:
Feign 除了能簡化服務調用,也可以實現當調用的服務失敗時,友好的反饋信息。
作者:blog.csdn.net/qq_21790633/article/details/105182750
來源:君寶逍遙
本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源:https://mp.weixin.qq.com/s/PYdBWWqhA6ONG0EBzuFssg