Learning blog: [SpringCloud] Feign

The difference between Feign and Ribbon is that Ribbon uses microservice names to access and uses RestTemplate to encapsulate Http requests, while Feign further encapsulates them on this basis, using interfaces and annotations, which will make writing Http clients easier. Feign is more readable than Ribbon, but its performance is lower


project structure
insert image description here

import dependencies

        <!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-openfeign -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
            <version>3.1.3</version>
        </dependency>

Service interface, open annotation @FeignClient

@FeignClient(value = "http://SPRINGCLOUD-PROVIDER-DEPT")
public interface DeptClientService {
    
    

    @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);
}


Project Structure
insert image description here
Configuration File

server:
  port: 80

spring:
  application:
    name: SPRINGCLOUD-CONSUMER-DEPT

eureka:
  client:
    service-url:
      defaultZone: http://localhost:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/
    register-with-eureka: false #不注册到eureka中
  instance:
    instance-id: springcloud-consumer-dept80  #描述信息
    prefer-ip-address: true #优先使用ip注册,访问显示ip

management:
  endpoints:
    web:
      exposure:
        include: "*"
  info:
    env:
      enabled: true

# 暴露端点info
info:
  app.name: yl-springcloud
  company.name: www.yl.com
  build.artifactId: com.yl.springcloud
  build.version: 1.0-SNAPSHOT

Controller

@RestController
public class DeptConsumerController {
    
    

    //消费者没有service
    //RestTemplate 直接调用 注册到spring
    //(URL,实体 Map, Class<T>,  responseType)

    @Autowired
    private DeptClientService service = null;

    @GetMapping("/consumer/dept/get/{id}")
    public Dept queryById(@PathVariable("id") Long id){
    
    
        return this.service.queryById(id);
    }

    @GetMapping("/consumer/dept/list")
    public List<Dept> queryAll(){
    
    
        return this.service.queryAll();
    }

    @PostMapping("/consumer/dept/add")
    public boolean addDept(Dept dept){
    
    
        return this.service.addDept(dept);
    }

}

Main startup class, open annotation @EnableFeignClients

@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients(basePackages = {
    
    "com.yl.springcloud"})
public class FeignDeptConsumer_80 {
    
    
    public static void main(String[] args) {
    
    
        SpringApplication.run(FeignDeptConsumer_80.class,args);
    }
}

insert image description here

Guess you like

Origin blog.csdn.net/Aurinko324/article/details/125657626