Java SpringCloud Bibbon
    RestTemplate.java

    1. package com.fcant.userservice.controller;
    2. import com.fcant.userservice.bean.Country;
    3. import com.fcant.userservice.bean.User;
    4. import org.slf4j.Logger;
    5. import org.slf4j.LoggerFactory;
    6. import org.springframework.beans.factory.annotation.Autowired;
    7. import org.springframework.web.bind.annotation.GetMapping;
    8. import org.springframework.web.bind.annotation.RequestMapping;
    9. import org.springframework.web.bind.annotation.RestController;
    10. import org.springframework.web.client.RestClientException;
    11. import org.springframework.web.client.RestTemplate;
    12. import java.util.ArrayList;
    13. import java.util.Collections;
    14. import java.util.List;
    15. /**
    16. * RestTemplateController
    17. * <p>
    18. * encoding:UTF-8
    19. *
    20. * @author Fcant 10:06 2019/12/9
    21. */
    22. @RestController
    23. @RequestMapping("/user")
    24. public class RestTemplateController {
    25. private static final Logger LOGGER = LoggerFactory.getLogger(RestTemplateController.class);
    26. private static final List<User> USER_LIST;
    27. static {
    28. List<User> userList = new ArrayList<>();
    29. userList.add(new User(1L, "User 01", "user01@fcant.com", "男", 1L, ""));
    30. userList.add(new User(2L, "User 02", "user02@fcant.com", "女", 2L, ""));
    31. USER_LIST = Collections.unmodifiableList(userList);
    32. }
    33. private RestTemplate restTemplate;
    34. @Autowired
    35. public RestTemplateController(RestTemplate restTemplate) {
    36. this.restTemplate = restTemplate;
    37. }
    38. @GetMapping("/rest-template")
    39. public List<User> queryUser(){
    40. List<User> userList = new ArrayList<>(USER_LIST);
    41. userList.forEach(user -> {
    42. Country country = null;
    43. try {
    44. country = restTemplate.getForObject("http://area-service/country/{countryId}",
    45. Country.class,
    46. user.getCountryId());
    47. user.setCountryName(country.getCountryName());
    48. } catch (RestClientException e) {
    49. e.printStackTrace();
    50. }
    51. });
    52. return userList;
    53. }
    54. }