这里就只是先简单的讲讲使用
上一篇说了建Eureka server和client,这次是在上次的基础上接着进行。
我写了两个client,一个叫demo3,一个叫demo4.现在是用demo4来调demo3的api接口。
首先demo3这个client上,正常的写一个接口。
@Controller
@RequestMapping("/demo3")
public class AnsController {
@RequestMapping(value = "/ans",method= RequestMethod.GET)
@ResponseBody
public String ans(){
return "hi demo4";
}
}
然后,我们再来写demo4,
pom中引入相关feign包,之前是spring-cloud-starter-feign这个报名,但是现在你去maven看会发现,这个已经不推荐使用了,现在用spring-cloud-starter-openfeign这个。
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
写一个service类,@FeignClient(name = "demo3"),name是你要调的那个服务的名字。fallback,这个属性是当你需要调的那个服务(本例里面的demo3)出问题了,就会走你fallback指定的实现类。不过要注意,demo4这个服务的配置文件里面要开启
feign:
hystrix:
enabled: true
不然fallback是不会生效的。
@RequestMapping(value = "/demo3/ans",method = RequestMethod.GET)这个里面的value是你要调的那个服务的api路径
@FeignClient(name = "demo3",fallback = HelloServiceImpl.class)
public interface HelloService {
@RequestMapping(value = "/demo3/ans",method = RequestMethod.GET)
String todo();
}
@Service
public class HelloServiceImpl implements HelloService{
@Override
public String todo() {
return "报错了,走这";
}
}
再写一个controller类
@Controller
@RequestMapping("/demo4")
public class HelloController {
@Autowired
private HelloService helloService;
@RequestMapping("/sayHi")
@ResponseBody
public String sayHi(){
String demo3 = "Hi demo3";
String demo4 = helloService.todo();
return demo3 +" "+demo4;
}
}
最后一步,启动类,加上@EnableFeignClients这个注解来开启feign功能
@EnableEurekaClient
@SpringBootApplication
@EnableFeignClients
public class Demo4Application {
public static void main(String[] args) {
SpringApplication.run(Demo4Application.class, args);
}
}
一开始我忘记加这个注解了,然后就报下面的错
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2019-01-31 16:16:34.401 ERROR 5472 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Field helloService in com.example.demo4.controller.HelloController required a bean of type 'com.example.demo4.service.HelloService' that could not be found.
The injection point has the following annotations:
- @org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'com.example.demo4.service.HelloService' in your configuration.
Disconnected from the target VM, address: '127.0.0.1:55181', transport: 'socket'
Process finished with exit code 1