千家信息网

spring cloud(四):Feign的应用

发表于:2024-10-23 作者:千家信息网编辑
千家信息网最后更新 2024年10月23日,1、概念Feign 是一种声明式、模板化的 HTTP 客户端,是一个声明web服务客户端,这便得编写web服务客户端更容易。2、应用2.1 、在项目中,模块与模块之间需要互相调用,比如web模块需要调
千家信息网最后更新 2024年10月23日spring cloud(四):Feign的应用

1、概念

Feign 是一种声明式、模板化的 HTTP 客户端,是一个声明web服务客户端,这便得编写web服务客户端更容易。


2、应用

2.1 、在项目中,模块与模块之间需要互相调用,比如web模块需要调用service模块的服务,这个时候就需要在web引入Fegin,创建项目web-fegin

2.2、在pom文件里面添加

org.springframework.cloud

spring-cloud-starter-feign

2.3、创建启动类WebFeignApplication

@SpringBootApplication

@EnableDiscoveryClient

@EnableFeignClients(basePackages="com.web")

public class WebFeignApplication{

public static void main(String[] args) {

SpringApplication.run(FeignApplication.class, args);

}

}

2.4、定义服务接口类UserFeignClient

@FeignClient(name =WebConstants.SERVIE_USER_NAME)

public interface UserFeignClient {

@RequestMapping("/{id}")

public User findByIdFeign(@RequestParam("id") Long id);

}

2.5、在web层调用Fegin

@RestController

public class FeignController {

@Autowired

private UserFeignClient userFeignClient;

@GetMapping("feign/{id}")

public User findByIdFeign(@PathVariable Long id) {

User user = this.userFeignClient.findByIdFeign(id);

return user;

}

}


2.6 如果不使用上面的fegin,则得自己写个服务调用类,来调用service的服务,增加编程的难度,既然有了fegin,就没必要重复造轮子了。


3、application.properties的配置

spring.application.name=web-fegin

server.port=8020

eureka.client.serviceUrl.defaultZone=http://localhost:9411/eureka/

service.user.name=microservice-provider-user

4、定义常量WebConstants

public class WebConstants{

public static final String SERVIE_USER_NAME="${service.user.name}";

}

5、访问

http://127.0.0.1:8020/fegin/1


6、总结:

其实通过Feign封装了HTTP调用服务方法,使得客户端像调用本地方法那样直接调用方法

0