Feign声明式REST调用

Feign声明式REST客户端

Feign是声明式、模板化的HTTP客户端,可以帮助我们更加便捷、优雅地调用HTTP API。
Feign的使用,创建一个接口,并在接口上添加注解即可,Feign支持自带的注解或者JAX-RS注解。Feign整合了Ribbon和Eureka。

创建Feign工程

复制micro-service-consumer-movie,命名为micro-service-consumer-movie-feign,修改pom文件,添加feign的依赖如下:

<?xml version="1.0" encoding="UTF-8"?>
<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>
	<groupId>com.test.cloud</groupId>
	<artifactId>micro-service-consumer-movie-feign</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<!-- 引入parent的依赖 -->
	<parent>
		<groupId>com.fanfan.cloud</groupId>
		<artifactId>micro-service-spring-cloud-study</artifactId>
		<version>0.0.1-SNAPSHOT</version>
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

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

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

	</dependencies>

	<build>
		<finalName>consumer-movie-feign</finalName>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
</project>

application.yml配置文件如下:

server:
  port: 8024
  
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/
  instance:
    prefer-ip-address: true
    instance-id: ${spring.application.name}:${spring.application.instance_id:${server.port}}
spring:
  application:
    name: cunsumer-movie-feign

创建一个Feign接口,添加@FeignClient注解:
可以看出使用非常简单,支持SpringMVC的注解,@FeignClient(“micro-service-provider”)指定客户端的名称,用于创建Ribbon负载均衡器。由于使用了Eureka,Ribbon会将micro-service-provider解析为Eureka Server服务注册表中的服务,还可以使用url属性指定url。

/**
 * Description:
 * Author:
 * Date:2019/1/26
 */
@FeignClient("micro-service-provider")
public interface UserFeignClient {
    /**
     * 注意不要用组合注解
     * @param id
     * @return
     */
    @RequestMapping(value = "/user/simple/{id}", method = RequestMethod.GET)
    User findById(@PathVariable("id") Long id);

    @RequestMapping(value = "/user/user", method = RequestMethod.POST)
    User postUser(@RequestBody User user);

    /**
     * GET请求传参为对象不会报错
     * @param user
     * @return
     */
    @RequestMapping(value = "/user/user", method = RequestMethod.GET)
    User getUser(User user);
}

接下来是Controller中的代码:

@RestController
public class MovieController {

    @Autowired
    private UserFeignClient userFeignClient;

    @GetMapping("/movie/{id}")
    public User findById(@PathVariable Long id) {
        return this.userFeignClient.findById(id);
    }

    @GetMapping("/test")
    public User testPost(User user) {
       return this.userFeignClient.postUser(user);
    }

    @GetMapping("/test/user")
    public User testGet(User user) {
        return this.userFeignClient.getUser(user);
    }

启动类如下:
需要添加@EnableFeignClients注解。

@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
public class ConsumerMovieFeignApplication {

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

自定义Feign的配置

在Spring Cloud中,Feign的默认配置类是FeignClientsConfiguration,该类定义Feign默认使用的编码器、解码器和契约。
由于Feign默认的契约是SpringMvcContract,使用自定义配置类可将其修改为Feign原生的默认契约。
复制micro-service-consumer-movie-feign,命名为:micro-service-consumer-movie-feign-custom。
在这里插入图片描述
application.yml配置如下:

server:
  port: 8026


eureka:
  client:
    serviceUrl:
      defaultZone: http://root:123456@localhost:8764/eureka/   # 使用需要密码验证的eureka
  instance:
    prefer-ip-address: true
    instance-id: ${spring.application.name}:${spring.application.instance_id:${server.port}}
spring:
  application:
    name: cunsumer-movie-feign-custom
logging:
  level:
   com.spring.cloud.movie.feign.UserFeignClient2:DEBUG     # 配置日志打印

在如下的配置类中设置了日志打印和HttpBasic认证:

/**
 * Description:
 * Author:
 * Date:2019/1/26
 */
@Configuration
public class FeignConfiguration {

    @Bean
    public Logger.Level feignLoggerLevel() {
        return feign.Logger.Level.FULL;
    }


    /**
     * 有些接口需要经过HTTP Basic的认证后才可以调用
     * 配置Eureka登录需要的账号和密码
     * @return
     */
    @Bean
    public BasicAuthRequestInterceptor basicAuthRequestInterceptor() {
        return new BasicAuthRequestInterceptor("root", "123456");
    }

}

注意FeignConfiguration这个配置文件不包含在主应用程序上下文的@ComponentScan注解中,否则这个配置将会被所有的@FeignClient共享。

/**
 * Description: 
 * Author:
 * Date:2019/1/29
 */
@FeignClient(name="micro-service-provider", configuration = FeignConfiguration.class)
public interface UserFeignClient {

    @RequestMapping(value = "/user/simple/{id}", method = RequestMethod.GET)
    User findById(@PathVariable("id") Long id);
}
@FeignClient(name="xxx",url="http://localhost:8764", configuration = FeignConfiguration.class)
public interface UserFeignClient2 {

    /**
     * 使用SpringMVC的注解
     * @param serviceName
     * @return
     */
    @RequestMapping(value="/eureka/apps/{serviceName}", method = RequestMethod.GET)
    String findServiceInfoFromEurekaByServiceName(@PathVariable("serviceName") String serviceName);

}

Controller层的代码如下:

/**
 * Description:
 * Author:
 * Date:2018/10/8
 */
@RestController
public class MovieController {

    @Autowired
    private UserFeignClient feignClient;

    @Autowired
    private UserFeignClient2 feignClient2;

    /**
     * 注意micro-service-provider服务不要引入security的jar包,否则会报错,认证没有起作用
     * "error":"Unauthorized","message":"Bad credentials"
     * @param id
     * @return
     */
    @GetMapping("/movie/{id}")
    public User findById(@PathVariable Long id) {
        return this.feignClient.findById(id);
    }


    /**
     * serviceName值为USER-HAHA(配置的appName)
     * @param serviceName
     * @return
     */
    @GetMapping("/{serviceName}")
    public String findServiceInfoFromEureka(@PathVariable String serviceName) {
        return this.feignClient2.findServiceInfoFromEurekaByServiceName(serviceName);
    }
    
}

使用Feign的原生契约

复制micro-service-consumer-movie-feign-custom,命名为:micro-service-consumer-movie-feign-custom-contract。
在这里插入图片描述
pom文件和application.yml文件按照需要修改名字和端口之类的即可。

Feign的配置类FeignConfiguration :

/**
 * Description:
 * Author:
 * Date:2019/1/26
 */
@Configuration
public class FeignConfiguration {

    /**
     * 将契约改成feign原生的契约
     * @return
     */
    @Bean
    public Contract feignContract() {
        return new feign.Contract.Default();
    }

}

然后在使用@FeignClient注解时指定配置类即可。


/**
 * Description:
 * Author:
 * Date:2019/1/26
 */

import com.spring.cloud.feign.FeignConfiguration;
import com.spring.jpa.consumer.entity.User;
import feign.Param;
import feign.RequestLine;
import org.springframework.cloud.netflix.feign.FeignClient;

@FeignClient(name="micro-service-provider", configuration = FeignConfiguration.class)
public interface UserFeignClient {

    @RequestLine("GET /user/simple/{id}")
    public User findById(@Param("id") Long id);

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值