使用fegin来进行远程调用

it2023-02-02  55

目录

1.Feign介绍2.使用2.1 修改模块 user模块2.2 改造pom2.3 改造启动类2.4 新建bookclient接口,和bookcontroller方法名参数名必须一致2.5 修改controller2.6 运行,效果相同

1.Feign介绍

Feign是Netflix公司开源的轻量级rest客户端,使用Feign可以非常方便的实现Http 客户端。Spring Cloud引入Feign并且集成了Ribbon实现客户端负载均衡调用。

2.使用

将上一个项目进行优化,feign 结合了ribbon 和resttemplate =>httpclient

2.1 修改模块 user模块

2.2 改造pom

<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- eureka 客户端的依赖--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> <!--&lt;!&ndash; ribbon负载均衡的依赖&ndash;&gt;--> <!--<dependency>--> <!--<groupId>org.springframework.cloud</groupId>--> <!--<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>--> <!--</dependency>--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency> <dependency> <groupId>com.wo</groupId> <artifactId>pojo</artifactId> <version>1.0-SNAPSHOT</version> </dependency> </dependencies> </project>

2.3 改造启动类

@SpringBootApplication //标注当前工程是eureka的客户端 @EnableEurekaClient //标注当前工程使用fegin来进行远程调用 feign 结合了ribbon 和resttemplate =>httpclient @EnableFeignClients public class UserSpringBootApplication { public static void main(String[] args) { SpringApplication.run(UserSpringBootApplication.class); } Springboot结合httpclient // @Bean // @LoadBalanced//开启负载均衡 // public RestTemplate restTemplate(){ // return new RestTemplate(); // } }

2.4 新建bookclient接口,和bookcontroller方法名参数名必须一致

//标注当前接口远程调用某个服务 @FeignClient(serviceId = "book") public interface BookClient { @RequestMapping("/findAll") public List<BookPojo> findAll(); @RequestMapping("/findById") public BookPojo findById(@RequestBody Map map); @RequestMapping("/delete") public void delete(@RequestBody Map map); @RequestMapping("/update") public void update(@RequestBody BookPojo bookPojo); @RequestMapping("/insert") public void insert(@RequestBody BookPojo bookPojo); }

2.5 修改controller

@RestController @RequestMapping("/user") public class UserController { @Autowired BookClient bookClient; @RequestMapping("/findAll") public List<BookPojo> findAll(){ return bookClient.findAll(); } @RequestMapping("/findById") public BookPojo findById(@RequestBody Map map){ return bookClient.findById(map); } @RequestMapping("/delete") public void delete(@RequestBody Map map){ bookClient.delete(map); } @RequestMapping("/update") public void update(@RequestBody BookPojo bookPojo){ bookClient.update(bookPojo); } @RequestMapping("/insert") public void insert(@RequestBody BookPojo bookPojo){ bookClient.insert(bookPojo); } }

2.6 运行,效果相同

最新回复(0)