第一步:使用Eclipse idea 创建spring start project;
第二步:修改pom.xml
第三步:添加调用远程服务接口,特别注意——如果被调服务配置了path,则@FeignClient也必须添加对应path
package com.test;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@FeignClient(name = "ServerProvider",path = "/ServerProvider")
public interface PersonService {
@RequestMapping(value = "/sayHelloService/sayHello",method = RequestMethod.POST)
String sayHelloToPerson();
}
第四步:添加Controller
package com.test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@RestController
@RequestMapping(value = "/getEurekaServiceByFeign")
public class PersonController {
@Autowired
private PersonService personService;
@RequestMapping("/sayHello")
public String sayHello() {
String result = personService.sayHelloToPerson();
return result;
}
}
第五步:启动类添加feign
package com.test;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class ConsumerFeignApplication {
public static void main(String[] args) {
SpringApplication.run(ConsumerFeignApplication.class, args);
System.out.println("* * * * * * * * * * * *");
System.out.println("* *");
System.out.println("* ConsumerFeign启动成功 *");
System.out.println("* *");
System.out.println("* * * * * * * * * * * *");
}
}
第六步:启动服务,在浏览器输入地址访问