您的位置:首页 > 编程语言 > Java开发

SpringCloud(六)springcloud feign

2017-01-16 22:21 411 查看
概念:

Feign是一个可声明式的webservice客户端。它能让调用webservice更加简单,通过对接口的注解便可轻松使用。spring cloud同时集成了Ribbon和Eureka来对Feign提供负载均衡。

大概使用:

Example spring boot app

@Configuration
@ComponentScan
@EnableAutoConfiguration
@EnableEurekaClient
@EnableFeignClients //添加Feign的注解
public class Application {

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

}
@FeignClient("stores") //用于通知Feign组件对该接口进行代理(不需要编写接口实现),使用者可直接通过[code]@Autowired
注入。
public interface StoreClient {
@RequestMapping(method = RequestMethod.GET, value = "/stores") //表示该方法向服务端发送http请求
List<Store> getStores();

@RequestMapping(method = RequestMethod.POST, value = "/stores/{storeId}", consumes = "application/json")
Store update(@PathVariable("storeId") Long storeId, Store store);
}[/code]

具体实现
package com.zhuyang.cloud;

import java.util.List;

import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.zhuyang.cloud.entity.User;

@FeignClient(value = "microservice-provider") //application name of service provider
public interface UserClientFeign {
// send "/service/all" to provider when findAll() involk
@RequestMapping(value = "/provider/service/all", method = RequestMethod.GET)
public List<User> findAll();

@RequestMapping(value = "/proiver/service/add", method = RequestMethod.POST)
public User addUser(@RequestBody User user);
}

package com.zhuyang.cloud.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.zhuyang.cloud.UserClientFeign;
import com.zhuyang.cloud.entity.User;

@RestController
public class MovieController {
@Autowired
UserClientFeign userClientFeign;//annotation of Feign

@RequestMapping(value = "/user/all", method = RequestMethod.GET) //handle request
public List<User> findAll() {
return userClientFeign.findAll();
}

@RequestMapping(value = "/user/add", method = RequestMethod.POST)
public User addUser(@RequestBody User user) {
return userClientFeign.addUser(user);
}
}


源码请参见https://github.com/zzzzzz5530041/microservice-consumer-feign
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: