Spring Cloud Feign的继承特性

Spring Cloud Feign提供了继承特性,可以进一步减少编码量,并提高可读性。

创建api工程:

命名为hello-service-api

pom.xml文件

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>com.zsy</groupId>
    <artifactId>zsy-parent</artifactId>
    <version>0.0.1-SNAPSHOT</version>
  </parent>
  <artifactId>hello-service-api</artifactId>
  <dependencies>
  		<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-feign -->
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-feign</artifactId>
		</dependency>
  </dependencies>
</project>

 编写实体类User


public class User {
 
    private String name;
 
    public User() {
    }
 
    public User(String name) {
        this.name = name;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 

 
}

编写HelloService接口:

@RequestMapping("/hello")
public interface HelloService {
 
    @RequestMapping(value = "/test1", method = RequestMethod.GET)
    String test1(@RequestParam("name") String name) ;
 
    @RequestMapping(value = "/test2", method = RequestMethod.POST)
    String test2(@RequestBody User user);
 
}

编写hello-service

pom.xml增加依赖:

<dependency>
    <groupId>com.zsy</groupId>
    <artifactId>hello-service-api</artifactId>
    <version>0.0.1-SNAPSHOT</version>
</dependency>

创建HelloController接口,实现hello-service-api中定义的接口HelloService

@RestController
public class HelloController implements HelloService {
 
    @Override
    public String test(@RequestParam("name") String name) {
        return "Hello " + name;
    }
 
 
    @Override
    public String test2(@RequestBody User user) {
        return "Hello "+ user.getName() + ", " + user.getAge();
    }
 
}

通过实现的方式,在Controller中不再包含以往会定义的请求映射注解@RequestMapping,在重写的时候会自动将注解带过来。在这个类中,除了实现接口的逻辑之外,只需要增加@RestController注解使该来成为一个REST接口类就可以了。

编写hello-consumer

编写RefactorHelloService接口,并继承hello-service-api包中的HelloService接口,然后添加@FeignClient注解来绑定服务。

@FeignClient(value = "HELLO-SERVICE")
public interface RefactorHelloService extends com.zsy.service.HelloService {
}

Controller类:

@RestController
public class ConsumerController {
    @Autowired
    RefactorHelloService refactorHelloService;
 
    @RequestMapping(value = "/feign-consumer", method = RequestMethod.GET)
    public String helloConsumer() {
        String result = refactorHelloService.test1("name");
        return result;
    }
 
}

上面例子为feign的继承特性调用服务,对比原本调用方式可减少代码和增加可读性,可维护性。

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值