一、通过Feign进行远程服务调用
数据库表信息
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for t_user
-- ----------------------------
DROP TABLE IF EXISTS `t_user`;
CREATE TABLE `t_user` (
`id` int NOT NULL AUTO_INCREMENT,
`username` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '用户名',
`password` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '密码',
`name` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '姓名',
`age` int NULL DEFAULT NULL COMMENT '年龄',
`balance` decimal(10, 0) NULL DEFAULT NULL COMMENT '账户余额',
`db` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '数据库',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of t_user
-- ----------------------------
INSERT INTO `t_user` VALUES (1, 'account1', NULL, '张三', 20, 100, '数据库1');
INSERT INTO `t_user` VALUES (2, 'account2', NULL, '李四', 28, 180, '数据库1');
SET FOREIGN_KEY_CHECKS = 1;
使用到的Maven依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
启动类
@SpringBootApplication
@EnableFeignClients //添加feign的启动注解
public class HomeworkStudentFeignApplication {
public static void main(String[] args) {
SpringApplication.run(HomeworkStudentFeignApplication.class, args);
}
}
编写通过feign进行调用应用的处理接口
@Service
@FeignClient(name = "HOMEWORK-PRODUCT")
public interface UserFeignClient {
@GetMapping("/get/{id}")
UserEntity getUser(@PathVariable("id") String id);
}
注意点:如果报异常说UserFeignClient的Bean未注册或这未找到,此处的 @Service 注解最好是加上。看了很多博客说将 spring-cloud-starter-openfeign 换成spring-cloud-openfeign-core ,我试了未能解决,所以又改回来了。解决的办法,就是加上@Service注解,删除之前的已经编译的文件,重启了IDEA。
二、Feign的日志打印
在yml中配置全局的日志输出级别
logging:
level:
com.demo.student.service.feign.UserFeignClient: DEBUG
可以对feign的日志输出级别,连接超时时间重定义
feign:
client:
config:
default:
connectTimeout: 5000
readTimeout: 5000
loggerLevel: full
encoder: feign.form.spring.SpringFormEncoder
compression:
request:
enabled: true
response:
enabled: true
更详细的参数信息请查看(FeignClientConfiguration类) 当查询时会在控制台中打印出相应的日志信息
三、Feign的自定义配置
首先需要修改feign的契约为其默认的契约
@Configuration
public class FeignConfig {
@Bean
public Contract feignContract(){
return new Contract.Default();
}
}
在feign的嗲用接口处指定加载契约组件
@Service
@FeignClient(name = "HOMEWORK-PRODUCT",configuration = {FeignConfig.class, FeignLogConfig.class})
public interface UserFeignClient {
@RequestLine("GET /get/{id}")
UserEntity getUser(@Param("id") String id);
}
注:此处需要使用RequestLine注解,并在里面指定请求方式是GET 还是POST,对于传递的参数,需要@Param进行标注。