Spring Cloud Alibaba 的學習之feign篇


是什么?

Feign 是一個聲明式的偽 HTTP 客戶端,它使得寫 HTTP 客戶端變得更簡單

為什么?

使用 Feign,只需要創建一個接口並注解。它具有可插拔的注解特性。Feign 支持可插拔的編碼器和解碼器。Feign 默認集成了 Ribbon,Nacos 也很好的兼容了 Feign,默認實現了負載均衡的效果

怎么做

提供者:

yml:

spring:
  application:
    name: puzzle-provider

  cloud:
    nacos:
      discovery:
        server-addr: 192.168.233.150:8848

server:
  port: 11000

management:
  endpoints:
    web:

application:

@SpringBootApplication
@EnableDiscoveryClient
public class PuzzleProviderApplication {
    public static void main(String[] args) {
        SpringApplication.run(PuzzleProviderApplication.class, args);
    }
}

service:

@Service
public class InitPuzzleServiceImpl implements InitPuzzleService {
    @Override
    public List initPuzzle() {
        List list= Arrays.asList("1", "2", "3","4","5","6","7","8","0");
        return list;
    }
}

controller

@RestController
public class InitPuzzleController {

    @Autowired
    private InitPuzzleService initPuzzleService;

    @GetMapping(value = "init")
    public List initPuzzle() {
        return initPuzzleService.initPuzzle();
    }
}

消費者:

yml:

spring:
  application:
    name: consumer-reset

  cloud:
    nacos:
      discovery:
        server-addr: 192.168.233.150:8848
feign:
  sentinel:
    enabled: true
server:
  port: 12000

management:
  endpoints:
    web:
      exposure:
        include: "*"

POM

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>

Application(主要添加EnableFeignClients)

@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class PuzzleResetApplication {
    public static void main(String[] args) {
        SpringApplication.run(PuzzleResetApplication.class, args);
    }
}

Service(@FeignClient("服務名") 注解來指定調用哪個服務)

@FeignClient(value = "puzzle-provider")
public interface ResetService {
    @GetMapping(value = "init")
    List initPuzzle();
}

Controller

@RestController
public class ResetController {

    @Autowired
    private ResetService resetService;

    @GetMapping("/reset")
    public List resetPuzzle(){
        List list = resetService.initPuzzle();
        Collections.shuffle(list);
        return list;
    }
}

配置負載均衡

修改 service-provider 服務的端口號如 11000,並啟動多個實例,IDEA 中依次點擊 Run -> Edit Configurations 並勾選 Allow parallel run 以允許 IDEA 多實例運行項目


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM