springcloud OpenFeign的使用

在这里只记录OpenFeign关键的使用步骤,A、B两个项目是基于springboot、springcloud实现的,并且在nacos中 有服务注册。

第一步:导入依赖

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

第二步:在springboot的启动类上面加一个注解@EnableFeignClients

@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class NacosConsumerDemoApplication {

    @Bean
    @LoadBalanced
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }

    public static void main(String[] args) {
        SpringApplication.run(NacosConsumerDemoApplication.class, args);
    }

}

第三步:在A项目中实现一个服务提供端的接口,等会被调用

@RestController
@RefreshScope
public class UserController {
    
    @Value("${spring.datasource.username}")
    private String username;

    @GetMapping("/tt")
    public String tt() {
        return username;
    }
}

第四步:在B项目中创建 OpenFeign 与服务提供者的调用接口,这里不需要关系接口的具体实现,定义一下就行。关键注解@FeignClient

//value中放的是被调用接口的所在服务名
@FeignClient(value = "provide")
public interface ProvideClient {

    @GetMapping("/tt")
    public String tt();


}

第五步: 在B项目中,第四步封装好了要调用的接口,服务调用者就可以直接调用了

@RestController
@RequestMapping("/auth")
@RefreshScope
public class ConsumerController {

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    ProvideClient provideClient;
    
    @GetMapping("/get")
    public String get() {
        String s = provideClient.tt();
        System.out.println("openfeign:" + s);
        return s;
    }

}
posted @ 2023-04-26 11:41  西红柿里没有番茄  阅读(46)  评论(0编辑  收藏  举报