实践Spring Cloud之Feign

Feign实现声明式服务调用,将REST服务包装成接口,效果类似本地调用一样

1
2
3
4
<dependency>
	<groupId>org.springframework.cloud</groupId>
	<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
1
@EnableFeignClients

接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/**
 * @author angi 
 */
@FeignClient("hello-service")
public interface HelloService {

	/**
	 * 无参
	 * 
	 * @return 
	 */
	@RequestMapping("/hello")
	String hello();

	@RequestMapping(value = "/hello1", method = RequestMethod.GET)
	String hello(@RequestParam("name") String name);

	/**
	 * 查询用户
	 * 
	 * @param name
	 * @param age
	 * @return
	 */
	@RequestMapping(value = "/hello2", method = RequestMethod.GET)
	User hello(@RequestHeader("name") String name, @RequestHeader("age") Integer age);

	/**
	 * 新增用户
	 * 
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/hello3", method = RequestMethod.POST)
	String hello(@RequestBody User user);
}

服务端

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/**
 * @author angi
 */
@RefreshScope
@RestController
public class HelloController {

    private final Logger logger = Logger.getLogger(getClass());

    @Value("${key2}")
    private String key;

    @Autowired
    private DiscoveryClient discoveryClient;

    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public String hello() throws Throwable {
        ServiceInstance instance = discoveryClient.getLocalServiceInstance();
        int sleepTime = new Random().nextInt(3000);
        Thread.sleep(sleepTime);
        logger.info("/hello, host:" + instance.getHost() + ", serviceId:" + instance.getServiceId());
        return "Hello, World!" + key;
    }

    @RequestMapping(value = "/hello1", method = RequestMethod.GET)
    public String hello(@RequestParam String name) {
        return "Hello, " + name;
    }

    /**
     * 查询用户
     *
     * @param name
     * @param age
     * @return
     */
    @RequestMapping(value = "/hello2", method = RequestMethod.GET)
    public User hello(@RequestHeader String name, @RequestHeader Integer age) {
        return new User(name, age);
    }

    /**
     * 新增用户
     *
     * @param user
     * @return
     */
    @RequestMapping(value = "/hello3", method = RequestMethod.POST)
    public String hello(@RequestBody User user) {
        return "Hello, " + user.getName() + ", " + user.getAge();
    }

}

feign默认使用断路器(hystrix)包裹所有方法,可以全局禁用,也可以局部禁用。

1
2
# 全局禁用hystrix
feign.hystrix.enabled=false