Feign and the Ribbon both do load balancing
- Eureka and Ribbon in SpringCloudChange the Ribbon to Feign
Create a Service in an API (POJO) project, just like a Service in a Service provider
- The interface name can be different, similar to Dubbo and Zookeeper
- The content of the interface should be consistent, and the service in the API should receive the same requests as the Controller in the service provider
steps
- Import dependence
- Write a Service in the entity class project
- Use the Service in the entity class project in the Controller that serves the consumer
- Import dependence
Import dependencies at the service provider
<dependencies>
<! -- Entity class -->
<dependency>
<groupId>org.example</groupId>
<artifactId>SpringCloud-Api</artifactId>
<version>1.0 the SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
</dependencies>
Copy the code
- Write a Service in the entity class project
@Service
@FeignClient(name= "SPRINGCLOUD-PROVIDER-DEPT")/ / value = service id
public interface FeignDeptService {
@RequestMapping(value = "/add")
boolean addDept(@RequestBody Dept dept);
@GetMapping("/byId/{id}")
Dept getById(@PathVariable(value = "id") int id);
@GetMapping("/getAll")
List<Dept> getAll(a);
}
Copy the code
- Use the Service in the entity class project in the service provider
@RestController
public class FeignDeptConsumerController {
// Consumer, there should be no service layer
//RestTemplate is a simple restful service template that provides multiple convenient methods for accessing remote HTTP services
@Autowired
private FeignDeptService feignDeptService;
@GetMapping("/consumer/add/")
public boolean add(Dept dept){
return feignDeptService.addDept(dept);
}
@GetMapping("/consumer/byId/{id}")
public Dept getDeptById(@PathVariable(value = "id") int id){
return feignDeptService.getById(id);
}
@GetMapping("/consumer/getAll")
public List getAll(a){
returnfeignDeptService.getAll(); }}Copy the code
summary
Notes used
-
@FeignClient
(name= “springCloud-provider-dept “)//value= service ID
On the Api interface
-
@EnableFeignClients
//(basePackages = {“com.cloud.service”})
On the service consumer’s startup class, that means scanning the interface that declares them to be the FeignClient client (via feignClient@feignClient). Scan code Configuration components, with org. Springframework. Context. The annotation. The Configuration @ the Configuration class