gpt4 book ai didi

java - 如何使用 Feign Client Spring Boot 从另一个服务获取数据(错误 : 406)

转载 作者:行者123 更新时间:2023-12-01 18:00:46 26 4
gpt4 key购买 nike

当我使用 Feign 客户端从一项服务(API 网关)调用另一项服务(用户服务)时,出现错误

有两个服务

  1. 用户服务
  2. API 网关

在我的 API 网关

FeignClient

@FeignClient(contextId = "user-by-email",name = "user-service")
@Service
public interface UserByEmail {
@RequestMapping(value = "/email/{email}", consumes= MediaType.APPLICATION_JSON_VALUE)
User findByEmail(@PathVariable("email") String email);
}

Controller

@RequestMapping("/test")
public class TestController {
@Autowired
private UserByEmail userByEmail;

@GetMapping(value = "/{email:.+}")
public ResponseEntity testUser(@PathVariable("email") String username) {
return ResponseEntity.ok(userByEmail.findByEmail(username));
}
}

我需要调用以下(用户服务)

Controller

@EnableFeignClients
@RestController
public class UserController extends BaseController<User> {
@Autowired
private UserService userService;

@PostConstruct
public void binder() {
init(this.userService);
}

@GetMapping(value = "/email/{email}")
public ResponseEntity findByEmail(@PathVariable("email") String email) {
return ResponseEntity.ok(userService.findByEmail(email));
}
}

存储库

@Override
public User findByEmail(String email) {
Query query = new Query(Criteria.where("email").is(email).and("status").is(1));
return mongoOperations.findOne(query, User.class);
}

服务

@Override
public User findByEmail(String email) {
return userDao.findByEmail(email);
}

我收到的错误是..

<Map>
<timestamp>1583924335777</timestamp>
<status>406</status>
<error>Not Acceptable</error>
<message>Could not find acceptable representation</message>
<trace>org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation&#xd;
at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:246)&#xd;

任何人都可以解释一下我的代码有什么问题,并提供您宝贵的解决方案

(基本上我需要在API网关中创建Security,以控制其他服务的访问)

最佳答案

尝试如下实现 Feign 客户端:

@FeignClient(name = "user-service")
public interface UserByEmail {

@RequestMapping(method = RequestMethod.GET, value = "/email/{email}", consumes = "application/json")
User findByEmail(@PathVariable("email") String email);

}

还要确保字段通过 JSON 匹配器 User POJO 传递。

关于java - 如何使用 Feign Client Spring Boot 从另一个服务获取数据(错误 : 406),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60634792/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com