2016-10-10 16 views
2

私はspring resttemplateとresttemplatebuilderについてのクエストを持っています。 resttemplatebuilderは、RestTemplateのための何らかの種類の工場です。私はそれを使用する方法についていくつかの質問があります。春の休憩テンプレートと残りのテンプレートビルダー

  1. を非常に多くの例では、インターネット上の私は@Configurationクラスでこのような何かを参照してください。

    @Bean 
    public RestTemplate getRestClient() { 
        RestTemplate restClient = new RestTemplate(); 
        ... 
        return restClient; 
    } 
    

    RestTemplate@Serviceクラスごとにインスタンス化することはないでしょうか?もしそうなら、それをカスタマイズする方法は?

  2. 春の参考資料RestTemplateBuilderRestTemplateCustomizerでカスタマイズする必要があります。 1人のビルダーで多くのIPアドレスから多くのURIを管理するには?

  3. RestTemplateBuilder経由ですべてのRestTemplatesにglobaly basicAuthenticationを追加する方法 - または何が良いのか?

ありがとうございました。

UPDATE:

私のアプリケーションは、異なるIPのとURLの多くのサーバから残りのサービスを呼び出す - ので、論理的に私のために、私は多くのRestTemplatesを持っている状況があります。

私はサーバごとに工場(RestTemplateBuilder)を持っています。サーバA、B、Cと言いましょう。私は基本認証を追加する方法を知っています。しかし、たとえば、サーバーAの基本認証は必要ですが、サーバーBの認証は必要ありませんか?

私はサーバ1台につきRestTemplateBuilderがあると考えていました。私は手動でこれをやりたくはありませんが、Springのメカニズムを使用します。

助けが必要ですか?

+0

about basicAuthentication - http://stackoverflow.com/questions/21920268/basic-authentication-for-rest-api-using-spring-resttemplate – aybekbuka

+0

私は基本認証を追加する方法を知っています。私はそれをクライアントリクエストの一部として追加するための優れたアーキテクチャ上の解決策を探しています。他の部分ではなく、@Serviceクラスごとにこれを手動で実行しないでください。 – javovy

答えて

5
  1. いいえ、通常はテンプレートインスタンスを休止していて、別のURLを渡して毎回パラメータを要求します。

    String result = restTemplate.getForObject("http://example.com/hotels/{hotel}/bookings/{booking}", String.class, vars); 
    
    Foo foo = restTemplate.getForObject(fooResourceUrl + "/1", Foo.class); 
    
  2. spring docからの記述例、あなたはどれRestTemplateCustomizer豆が自動的 自動設定RestTemplateBuilderに追加されますビルダー

    public class ProxyCustomizer implements RestTemplateCustomizer { 
    
        @Override 
        public void customize(RestTemplate restTemplate) { 
         HttpHost proxy = new HttpHost("proxy.example.com"); 
         HttpClient httpClient = HttpClientBuilder.create() 
           .setRoutePlanner(new DefaultProxyRoutePlanner(proxy) { 
    
            @Override 
            public HttpHost determineProxy(HttpHost target, 
              HttpRequest request, HttpContext context) 
                throws HttpException { 
             if (target.getHostName().equals("192.168.0.5")) { 
              return null; 
             } 
             return super.determineProxy(target, request, context); 
            } 
    
           }).build(); 
         restTemplate.setRequestFactory(
           new HttpComponentsClientHttpRequestFactory(httpClient)); 
        } 
    
    } 
    

にできるだけ多くのカスタマイザを追加することができます。さらに、追加のカスタマイザを持つ新しい RestTemplateBuilderは 呼び出すadditionalCustomizers(RestTemplateCustomizer ...)によって作成することができ

@Bean 
public RestTemplateBuilder restTemplateBuilder() { 
    return new RestTemplateBuilder() 
     .rootUri(rootUri) 
     .basicAuthorization(username, password); 
} 
1

私はこのように私の設定を設定している:

@Bean 
public RestTemplateCustomizer restTemplateCustomizer() { 
    return restTemplate -> { 
     restTemplate.setRequestFactory(clientHttpRequestFactory()); 
    }; 
} 

@Bean 
public ClientHttpRequestFactory clientHttpRequestFactory() { 
    SimpleClientHttpRequestFactory clientHttpRequestFactory = new SimpleClientHttpRequestFactory(); 
    clientHttpRequestFactory.setConnectTimeout(connectionTimeoutMs); 
    clientHttpRequestFactory.setReadTimeout(connectionTimeoutMs); 
    clientHttpRequestFactory.setBufferRequestBody(false); 
    return clientHttpRequestFactory; 
} 

たび春の注入RestTemplateBuilderでは、このRestTemplateCustomizerを使用してClientHttpRequestFactoryを使用するように構成します。いくつかの異なるカスタマイズを行う必要があるかもしれません。そうでない場合は、Beanを宣言しないでください。

認証ヘッダーを追加するには、ユーザー名とパスワードを知っている必要があります。ユーザー名とパスワードは、実行時まで知ることができません。

@Component 
public class Authenticator { 

    @Autowired 
    private RestTemplateBuilder restTemplateBuilder; 

    public void withAuthenticationHeader(String username, String password, Consumer<RestTemplate> doAuthenticated) { 
     RestTemplate restTemplate = 
      restTemplateBuilder 
       .basicAuthorization(username, password) 
       .build(); 

     try { 
      doAuthenticated.accept(restTemplate); 

     } catch (HttpClientErrorException exception) { 
      // handle the exception 
     } 
    } 
} 

これは私が、私は自分のアプリケーションに必要なもので、すべての要求のための標準的な方法で認証の失敗を処理することができます:だから私は、オーセンティケータBeanを作成しました。

他のBeanに注入し、そのように使用されます。

@Autowired 
private Authenticator authenticator; 

public void transmit() { 
    authenticator.withAuthenticationHeader(username, password, restTemplate -> 
     restTemplate.postForLocation(url, request)); 
} 

だから、あなたが直接RestTempleを使用するのではなく、認証を使用すると思います。 この種の標準パターンは見つかりませんでしたが、これはうまくいくようです。

関連する問題