欢迎访问Spring Cloud中国社区

《重新定义Spring Cloud实战》由Spring Cloud中国社区倾力打造,基于Spring Cloud的Finchley.RELEASE版本,本书内容宽度足够广、深度足够深,而且立足于生产实践,直接从生产实践出发,包含大量生产实践的配置。欢迎加微信Software_King进群答疑,国内谁在使用Spring Cloud?欢迎登记

spring cloud RestTemplate访问其他服务名错误

雨哥 · 7月前 · 766 ·

报错截图

—————spring cloud RestTemplateConfig 封装类

package com.mooc.house.api.config;

import java.nio.charset.Charset;
import java.util.Arrays;

import org.apache.http.client.HttpClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter4;

@Configuration
public class RestAutoConfig {

  1. public static class RestTemplateConfig {
  2. @Bean
  3. @LoadBalanced //spring 对restTemplate bean进行定制,加入loadbalance拦截器进行ip:port的替换
  4. RestTemplate lbRestTemplate(HttpClient httpclient) {
  5. RestTemplate template = new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpclient));
  6. template.getMessageConverters().add(0,new StringHttpMessageConverter(Charset.forName("utf-8")));
  7. template.getMessageConverters().add(1,new FastJsonHttpMessageConvert5());
  8. return template;
  9. }
  10. @Bean
  11. RestTemplate directRestTemplate(HttpClient httpclient) {
  12. RestTemplate template = new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpclient));
  13. template.getMessageConverters().add(0,new StringHttpMessageConverter(Charset.forName("utf-8")));
  14. template.getMessageConverters().add(1,new FastJsonHttpMessageConvert5());
  15. return template;
  16. }
  17. public static class FastJsonHttpMessageConvert5 extends FastJsonHttpMessageConverter4{
  18. static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
  19. public FastJsonHttpMessageConvert5(){
  20. setDefaultCharset(DEFAULT_CHARSET);
  21. setSupportedMediaTypes(Arrays.asList(MediaType.APPLICATION_JSON,new MediaType("application","*+json")));
  22. }
  23. }
  24. }

}

package com.mooc.house.api.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**

  • 既支持直连又支持服务发现的调用
    /
    @Service
    public class GenericRest {

    @Autowired
    private RestTemplate lbRestTemplate;

    @Autowired
    private RestTemplate directRestTemplate;

    private static final String directFlag = “direct://“;

    public <T> ResponseEntity<T> post(String url,Object reqBody,ParameterizedTypeReference<T> responseType){

    1. RestTemplate template = getRestTemplate(url);
    2. url = url.replace(directFlag, "");
    3. return template.exchange(url, HttpMethod.POST,new HttpEntity(reqBody),responseType);

    }

    public <T> ResponseEntity<T> get(String url,ParameterizedTypeReference<T> responseType){

    1. RestTemplate template = getRestTemplate(url);
    2. url = url.replace(directFlag, "");
    3. return template.exchange(url, HttpMethod.GET,HttpEntity.EMPTY,responseType);

    }

    private RestTemplate getRestTemplate(String url) {

    1. if (url.contains(directFlag)) {
    2. return directRestTemplate;
    3. }else {
    4. return lbRestTemplate;
    5. }

    }

}


消费者controller

package com.mooc.house.api.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.mooc.house.api.common.ResultMsg;
import com.mooc.house.api.model.User;
import com.mooc.house.api.service.AccountService;

@Controller
public class UserController {

  1. @Autowired
  2. private AccountService accountService;
  3. //----------------------------注册流程-------------------------------------------
  4. @RequestMapping(value="accounts/register",method={RequestMethod.POST,RequestMethod.GET})
  5. public String accountsSubmit(User account,ModelMap modelMap){
  6. if (account == null || account.getName() == null) {
  7. // modelMap.put("agencyList", agencyService.getAllAgency());
  8. return "/user/accounts/register";
  9. }
  10. ResultMsg retMsg = UserHelper.validate(account);
  11. if (retMsg.isSuccess()) {
  12. boolean exist = accountService.isExist(account.getEmail());
  13. if (!exist) {
  14. accountService.addAccount(account);
  15. modelMap.put("email", account.getEmail());
  16. return "/user/accounts/registerSubmit";
  17. }else {
  18. return "redirect:/accounts/register?" + retMsg.asUrlParams();
  19. }
  20. }else {
  21. return "redirect:/accounts/register?" + retMsg.asUrlParams();
  22. }

}

  1. @RequestMapping("accounts/verify")
  2. public String verify(String key){
  3. boolean result = accountService.enable(key);
  4. if (result) {
  5. return "redirect:/index?" + ResultMsg.successMsg("激活成功").asUrlParams();
  6. }else {
  7. return "redirect:/accounts/signin?" + ResultMsg.errorMsg("激活失败,请确认链接是否过期").asUrlParams();
  8. }
  9. }

}


Dao层

package com.mooc.house.api.dao;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Repository;

import com.google.common.collect.Lists;
import com.mooc.house.api.common.RestResponse;
import com.mooc.house.api.config.GenericRest;
import com.mooc.house.api.model.User;

@Repository
public class UserDao {

  1. @Autowired
  2. private GenericRest rest;
  3. @Value("${user.service.name}")
  4. private String userServiceName;
  5. public List<User> getUserList(User query) {
  6. ResponseEntity<RestResponse<List<User>>> resultEntity =
  7. rest.post("http://"+ userServiceName + "/user/getList",
  8. // rest.post("http://localhost:8083/user/getList",
  9. query, new ParameterizedTypeReference<RestResponse<List<User>>>() {});
  10. RestResponse<List<User>> restResponse = resultEntity.getBody();
  11. if (restResponse.getCode() == 0) {
  12. return restResponse.getResult();
  13. }else {
  14. return Lists.newArrayList();
  15. }

}

  1. public User addUser(User account) {
  2. String url = "http://" + userServiceName + "/user/add";