SpringCloud2.0.2 服务注入与发送Feign请求

主要是针对Spring Cloud新出的版本(2.0.2.RELEASE),一些新的改动,与在使用中遇见的一些问题,踩过的坑,希望后面的人就不用踩了。

服务注入到Eureka需要的MAVEN配置

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

如果找不到包加入下面:

<dependencyManagement>
	<dependencies>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-dependencies</artifactId>
			<version>${spring-cloud.version}</version>
			<type>pom</type>
			<scope>import</scope>
		</dependency>
	</dependencies>
</dependencyManagement>

如果还是不行,再加

<repositories>
	<repository>
		<id>spring-snapshots</id>
		<name>Spring Snapshots</name>
		<url>https://repo.spring.io/snapshot</url>
		<snapshots>
			<enabled>true</enabled>
		</snapshots>
	</repository>
	<repository>
		<id>spring-milestones</id>
		<name>Spring Milestones</name>
		<url>https://repo.spring.io/milestone</url>
		<snapshots>
			<enabled>false</enabled>
		</snapshots>
	</repository>
</repositories>

这个呢,是因为比较新,maven可能还么相关的包。

application.yml配置

spring:
  application:
    name: deal-center
server:
  port: 8902
eureka:
  client:
    serviceUrl:
      defaultZone: http://admin:[email protected]:8000/eureka/

启动类

@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
public class DealCentreApplication {

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

编写Feign接口类

@FeignClient("user-center")
public interface UserService {
	@GetMapping("/user/getUserById")
	public User getUserById(@RequestParam("id")Long id);
	
	@GetMapping("/user/getById/{id}")
	public User getById(@PathVariable("id")Long id);
	
	@GetMapping("/user/queryUserList")/*这个是不对的*/
	public List<User> queryUserList(@RequestBody User user);
}

Feign请求类中,第一个和第二个,都可以请求通。第三个不行。如果都换成POST请求,也可以请求正确。
在SpringCloud 1.5版本的时候,@GetMapping和@PostMapping不支持,现在已经可以了。但是复杂参数时还说不行,报错如下:

UserService#queryUserList(User); content: 
{"timestamp":"2018-05-30T09:15:02.095+0000","status":405,"error":"Method Not Allowed","message":"Request method 'POST' not supported","path":"/user/queryUserList"}

意思是说不支持POST请求,可是明明发的是POST请求啊,跟代码走...发现一段代码如下:

privatesynchronizedOutputStream getOutputStream0()throwsIOException {
	try{
		if(!this.doOutput) {
			thrownewProtocolException("cannot write to a URLConnection if doOutput=false - call setDoOutput(true)");
		}else{
			if(this.method.equals("GET")) {
				this.method ="POST";
			}
		}
	}
}

估计因为考虑到restful风格吧,所以建议还说用POST请求,那么真要用GET怎么玩呢?
我采用apach的httpclient替换掉Feign默认使用的连接工具实现类(还没解决,谁有好的解决方案啊?)

说说项目结构

猜你喜欢

转载自my.oschina.net/bianxin/blog/1821684