Feignを使用して宣言的なREST呼び出しを実装します
前:springcloud認証セキュリティ
次:Feignによる圧縮のサポート
フェギンの紹介
前の例では、RestTemplateを使用してREST API呼び出しを実装しています。コードは、おおまかに次のとおりです。
@RequestMapping("user/{id}")
public User findById(@PathVariable("id") Integer id){
User user = restTemplate.getForObject("http://provider/user/"+id, User.class);
return user;
}
文字列を連結してURLを作成しますが、URLにはパラメータが1つしかありません。ただし、実際には、URLには複数のパラメータが含まれていることがよくあります。この時点でURLがこのように構成されていると、非常に非効率になり、保守が困難になります。たとえば、次のようなURLをリクエストするとします。
http:// localhost:8010 / search?name =张三&username = account1&age = 20
ここで、URLには3つのパラメーターのみが含まれています。URLが10を超えるパラメーターなど、より複雑な場合、コードの保守が困難になります。
消費者のためにFeignを統合する
1pom.xmlにFeign依存関係を追加します
<!--springboot1.5.9版本适用-->
<!--
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
<version>1.4.7.RELEASE</version>
</dependency>
-->
<!--springboot 2.1版本适用 -->
<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-openfeign -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
<version>2.1.3.RELEASE</version>
</dependency>
2 Feignインターフェースを作成し、@ FeignClentアノテーションを追加し
ます。インターフェースはプロバイダーのメソッドと一致しています。
import com.itzz.springcloudconsumer.pojo.User;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@FeignClient(name = "provider")
@Component
public interface UserFeignClient {
@RequestMapping("user/{id}")
public User findById(@PathVariable(value = "id") Integer id);
}
3コントローラーを変更してFeignインターフェースを呼び出し、
UserFeignClientインターフェースを自動的に挿入すると、インターフェースは内部のfindByIdメソッドを呼び出します。
@RestController
public class UserController {
@Autowired
private UserFeignClient userFeignClient;
@Autowired
private RestTemplate restTemplate;
@Value("${user.userServiceUrl}")
private String userServiceUrl;
@RequestMapping("user/{id}")
public User findById(@PathVariable("id") Integer id){
// return restTemplate.getForObject("http://provider/user/"+id, User.class);
// return restTemplate.getForObject(userServiceUrl+id,User.class);
return userFeignClient.findById(id);
}
}
4スタートアップクラスを変更し、@ EnableFeignClientsアノテーションを追加します。
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
public class SpringcloudConsumerApplication {
@Bean
@LoadBalanced
public RestTemplate restTemplate(){
return new RestTemplate();
}
/**自定义配置ribbon负载均衡算法
* @return
*/
@Bean
public IRule myRule(){
// return new RoundRobinRule();//轮询
return new RandomRule();
// return new RetryRule();//重试
// return new BestAvailableRule();
}
public static void main(String[] args) {
SpringApplication.run(SpringcloudConsumerApplication.class, args);
}
}
5コンシューマープロジェクトをテストして再起動し
ます。アクセスできれば問題ありません。
urlに複数のパラメータを指定したREST呼び出し
マルチパラメータurlメソッドをプロバイダーに追加する
1つは安らかなスタイルで、もう1つは以下に示すようにパラメータを渡す通常の方法です。
import com.itzz.springcloudprovider.dao.UserRepository;
import com.itzz.springcloudprovider.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.jws.soap.SOAPBinding;
import java.util.List;
@RestController
public class UserController {
@Autowired
private UserRepository userRepository;
@GetMapping("user/{id}")
public User findById(@PathVariable(value = "id") Integer id){
return userRepository.getOne(id);
}
//restful传多个参
//http://localhost:8000/search/1/张三/zhangsan
@GetMapping("search/{id}/{username}/{name}")
public User search(@PathVariable(value = "id") Integer id,@PathVariable("username") String username,@PathVariable("name") String name){
return userRepository.getOne(id);
}
//http://localhost:8000/search2?id=1&username=zhangsan&name=张三
@GetMapping("search2")
public User search2(Integer id,String username,String name){
return userRepository.getOne(id);
}
}
2関連するインターフェースをコンシューマープロジェクトのUserFeignClientインターフェースに追加します。
//restful传多个参
@RequestMapping("search/{id}/{username}/{name}")
public User search(@PathVariable(value = "id") Integer id,@PathVariable("username") String username,@PathVariable("name") String name);
@RequestMapping("search2")
public User search2(@RequestParam("id") Integer id, @RequestParam("username") String username, @RequestParam("name") String name);
注:偽のインターフェース:複数のパラメーターがある場合は、@ RequestParamアノテーションを使用してパラメーター名を指定する必要があります。
3コンシューマーのコントローラーにUserFeignClient関連のインターフェイスの呼び出しを実装します
@RestController
public class UserController {
@Autowired
private UserFeignClient userFeignClient;
@Autowired
private RestTemplate restTemplate;
@Value("${user.userServiceUrl}")
private String userServiceUrl;
@RequestMapping("user/{id}")
public User findById(@PathVariable("id") Integer id){
// return restTemplate.getForObject("http://provider/user/"+id, User.class);
// return restTemplate.getForObject(userServiceUrl+id,User.class);
return userFeignClient.findById(id);
}
@RequestMapping("search/{id}/{username}/{name}")
public User search(@PathVariable("id") Integer id,@PathVariable("username") String username,@PathVariable("name") String name){
return userFeignClient.search(id, username, name);
}
@RequestMapping("search2/{id}/{username}/{name}")
public User search2(@PathVariable("id") Integer id,@PathVariable("username") String username,@PathVariable("name") String name){
return userFeignClient.search2(id, username, name);
}
}
5テスト
最初にプロバイダーを使用して
http:// localhost:8001 / search / 3 / zhangsan / zz
にアクセスし、次にコンシューマーを使用して
http:// localhost:8011 / search / 3 / zhangsan / zzにアクセスします。