Feign負載均衡
阿新 • • 發佈:2021-10-14
目錄
Feign負載均衡:
Feign服務模組建立介面:
匯入依賴:
<!--feign依賴-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
<version>1.4.6.RELEASE</version>
</dependency>
介面:
package com.stt.springcloud.service; import com.stt.springcloud.pojo.Dept; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.stereotype.Component; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import java.util.List; @Component @FeignClient(value = "SPRINGCLOUD-PROVIDER-DEPT") // 宣告去哪裡取,配置服務名稱 public interface DeptClientService { // 以下的三個介面是SPRINGCLOUD-PROVIDER-DEPT這個微服務中的介面,在這裡做宣告 @GetMapping("/dept/get/{id}") public Dept queryById(@PathVariable("id") Long id); @GetMapping("/dept/list") public List<Dept> queryAll(); @PostMapping("/dept/add") public boolean addDept(Dept dept); }
啟動類:
開啟Feign並掃描介面包,開啟註解掃描
package com.stt; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; import org.springframework.cloud.openfeign.EnableFeignClients; import org.springframework.context.annotation.ComponentScan; @SpringBootApplication @EnableEurekaClient @EnableFeignClients(basePackages = "com.stt.springcloud") // 啟動Feign,掃描包 @ComponentScan("com.stt.springcloud") // 掃描註解 public class FeignDeptConsumer_80 { public static void main(String[] args) { SpringApplication.run(FeignDeptConsumer_80.class, args); } }
建立Feign的服務消費者:
使用面向介面呼叫,取代了原有的RestTemplate,使用服務名呼叫
@RestController public class DeptConsumerController { // 注入Feign中宣告的Service @Autowired private DeptClientService deptClientService; @RequestMapping("/consumer/dept/add") public boolean get(Dept dept){ return deptClientService.addDept(dept); } @RequestMapping("/consumer/dept/get/{id}") public Dept get(@PathVariable("id") Long id){ return deptClientService.queryById(id); } @RequestMapping("/consumer/dept/list") public List<Dept> get(){ return deptClientService.queryAll(); } }