Настройка интерфейса Spring @httpexchange для использования на основе свойстваJAVA

Программисты JAVA общаются здесь
Anonymous
Настройка интерфейса Spring @httpexchange для использования на основе свойства

Сообщение Anonymous »

Я хотел бы иметь возможность настроить интерфейс Spring @httpexchange для использования через Application.properties .
Существует две внешние службы, которые обнажают конечную точку REST. Я не владею ни одной из двух услуг, и эти две службы даже не знают друг о друге. http://some-gold-price-service.com/getprice написан@RestController
public class GoldPriceController {

@GetMapping("/getPrice")
public Map getGoldPrice() throws InterruptedException {
Thread.sleep(800);
System.out.println("getGoldPrice");
int randomNum = (int)(Math.random() * 101);
return Map.of("price", String.valueOf(randomNum));
}

}


[*] на http://company-for-stock.co.uk/getprice:
@RestController
public class StockPriceController {

@GetMapping("/getPrice")
public Map getStockPrice() throws InterruptedException {
Thread.sleep(800);
System.out.println("Get Stock Price");
int randomNum = (int)(Math.random() * 101);
return Map.of("price", String.valueOf(randomNum));
}

}



Как вы можете видеть, не зная друг друга, кажется, что они предлагают ответ полезной нагрузки, который содержит цену, и аналогичный/getprice конечная точка. Пружина): < /p>
@Bean(name = "gold")
RestClient restGoldClient(RestClient.Builder builder, OAuth2ClientHttpRequestInterceptor interceptor) {
return builder
.baseUrl("http://some-gold-price-service.com/")
.requestInterceptor(interceptor)
.build();
}

@Bean(name = "stock")
RestClient restStockClient() {
return RestClient.builder()
.baseUrl("http://company-for-stock.co.uk/")
.requestInterceptor(...)
.defaultHeader("AUTHORIZATION", fetchToken())
.messageConverters(...)
.requestFactory(clientHttpRequestFactory())
.build();
}
< /code>
@Configuration
public class RestClientGoldConfiguration {

@Bean
public GoldPriceHttpExchange goldPriceHttpExchange(RestClient restGoldClient) {
return HttpServiceProxyFactory.builderFor(RestClientAdapter.create(restClient)).build().createClient(GoldPriceHttpExchange.class);
}

}
< /code>
@Configuration
public class RestClientStockConfiguration {

@Bean
public StockPriceHttpExchange stockPriceHttpExchange(RestClient restStockClient) {
return HttpServiceProxyFactory.builderFor(RestClientAdapter.create(restClient)).build().createClient(StockPriceHttpExchange.class);
}
}

Обратите внимание, каждый сайт имеет свою собственную аудиторию и т. Д. Поэтому нам также нужны два RestClient . Теперь они поддаются смене.@HttpExchange(accept = "application/json")
public interface GoldPriceHttpExchange {

@GetExchange("/getPrice")
Map getPrice();

}
< /code>
@HttpExchange(accept = "application/json")
public interface StockPriceHttpExchange {

@GetExchange("/getPrice")
Map getPrice();

}

и, наконец, служба с использованием двух httpexchange :
@Autowired
GoldPriceHttpExchange goldPriceHttpExchange;

@Autowired
StockPriceHttpExchange stockPriceHttpExchange;

public String getSomePriceDependingOnConfiguration() {
// Map priceResponse = goldPriceHttpExchange.getPrice();
Map priceResponse = stockPriceHttpExchange.getPrice();

return priceResponse.get("price");
}

As of right now, when we need the service to get the price for gold, we comment the other line //Map priceResponse = stockPriceHttpExchange.getPrice(); and rebuild the app, then configure the URL in application properties to http://some-gold-price-service.com/getPrice to then redeploy Приложение полностью.
наоборот, если нам нужно получить цену акций, мы прокомментируем другую строку // map priceresponse = goldpricehttpexchange.getprice (); и снова, восстановить приложение, настроить приложение. http://company-for-stock.co.uk/getprice и снова разверните приложение. PrettyPrint-Override ">@Autowired
GoldPriceHttpExchange goldPriceHttpExchange;

@Autowired
StockPriceHttpExchange stockPriceHttpExchange;

public String getSomePriceDependingOnConfiguration() {
Map priceResponse = {get either goldPriceHttpExchange bean or stockPriceHttpExchange bean based on a property}.getPrice();

return priceResponse.get("price");
}


Подробнее здесь: https://stackoverflow.com/questions/795 ... a-property

Вернуться в «JAVA»