Call another rest api from my server in Spring-Boot

前端 未结 5 1491
北恋
北恋 2020-12-01 01:30

I want to call another web-api from my backend on a specific request of user. For example, I want to call Google FCM send message api to send a message to a

5条回答
  •  不思量自难忘°
    2020-12-01 01:50

    Modern Spring 5+ answer using WebClient instead of RestTemplate.

    Configure WebClient for a specific web-service or resource as a bean (additional properties can be configured).

    @Bean
    public WebClient localApiClient() {
        return WebClient.create("http://localhost:8080/api/v3");
    }
    

    Inject and use the bean from your service(s).

    @Service
    public class UserService {
    
        private static final Duration REQUEST_TIMEOUT = Duration.ofSeconds(3);
    
        private final WebClient localApiClient;
    
        @Autowired
        public UserService(WebClient localApiClient) {
            this.localApiClient = localApiClient;
        }
    
        public User getUser(long id) {
            return localApiClient
                    .get()
                    .uri("/users/" + id)
                    .retrieve()
                    .bodyToMono(User.class)
                    .block(REQUEST_TIMEOUT);
        }
    
    }
    

提交回复
热议问题