欢迎访问Spring Cloud中国社区

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

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

雨哥 · 3月前 · 417 ·

报错截图

—————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";
  3. //String url = "http://localhost:8083//user/add";
  4. ResponseEntity<RestResponse<User>> responseEntity = rest.post(url,account, new ParameterizedTypeReference<RestResponse<User>>() {});
  5. RestResponse<User> response = responseEntity.getBody();
  6. if (response.getCode() == 0) {
  7. return response.getResult();
  8. }{
  9. throw new IllegalStateException("Can not add user");
  10. }
  11. }
  12. /**
  13. * 用户激活
  14. * @param key
  15. */
  16. public boolean enable(String key) {

// Rests.exc(() ->{
// String url = Rests.toUrl(userServiceName, “/user/enable?key=” + key);
// ResponseEntity<RestResponse<Object>> responseEntity =
// rest.get(url, new ParameterizedTypeReference<RestRespo


nse<Object>>() {});
// return responseEntity.getBody();
// }
// );
String url = “http://"+ userServiceName +”/user/enable?key=”+key;
// String url = “http://localhost:8083/user/enable?key="+key;
RestResponse<Object> response =
rest.get(url, new ParameterizedTypeReference<RestResponse<Object>>() {}).getBody();

  1. return response.getCode() == 0;
  2. }

}

——————————————————-消费者pom
<?xml version=”1.0” encoding=”UTF-8”?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.mooc.house</groupId>
<artifactId>api-gateway</artifactId>
<version>1.0.0-SNAPSHOT</version>
<packaging>jar</packaging>

<name>api-gateway</name>
<description>网关服务</description>

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.15.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<logbook.version>1.3.0</logbook.version>
<spring-cloud.version>Camden.SR7</spring-cloud.version>


</properties>

<dependencies>

<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.31</version>
</dependency>

<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.24</version>
</dependency>

<!-- spring boot 依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>


<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>



<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>


<dependency>
<groupId>org.zalando</groupId>
<artifactId>logbook-core</artifactId>
<version>${logbook.version}</version>
</dependency>
<dependency>
<groupId>org.zalando</groupId>
<artifactId>logbook-servlet</artifactId>
<version>${logbook.version}</version>
</dependency>
<dependency>
<groupId>org.zalando</groupId>
<artifactId>logbook-httpclient</artifactId>
<version>${logbook.version}</version>
</dependency>
<dependency>
<groupId>org.zalando</groupId>
<artifactId>logbook-spring-boot-starter</artifactId>
<version>${logbook.version}</version>
</dependency>


<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.4</version>
</dependency>

<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
</dependency>




<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>

</dependency>







<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>

</dependencies>

<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>1.5.15.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>

<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>


</project>

1




消费者application

server.port=8080
spring.application.name=api-gateway
management.port=8023
eureka.client.service-url.defaultZone=http://127.0.0.1:8666/eureka
eureka.client.register-with-eureka=false

logbook.write.level=info
logbook.format.style=http

user.service.name=user
house.service.name=house
comment.service.name=comment

spring.mail.host=smtp.163.com
spring.mail.username=spring_boot@163.com
spring.mail.password=abc123455
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true

spring.freemarker.cache=true
spring.freemarker.charset=UTF-8
spring.freemarker.content-type=text/html;charset=UTF-8
spring.freemarker.expose-request-attributes=true
spring.freemarker.expose-session-attributes=true

spring.freemarker.expose-spring-macro-helpers=true
spring.freemarker.allow-session-override=true
spring.freemarker.allow-request-override=true
spring.freemarker.suffix=.ftl

spring.freemarker.settings.datetime_format=yyyy-MM-dd HH:mm:ss
spring.freemarker.settings.default_encoding=UTF-8
spring.freemarker.settings.number_format=0.##########
spring.freemarker.settings.auto_import=common/common.ftl as common
spring.freemarker.settings.template_exception_handler=ignore
spring.freemarker.settings.template_update_delay=0

file.path=/Users/zeyu/Desktop/imgs

domain.name=127.0.0.1:8080

file.prefix=http://127.0.0.1:8081/images






生产者UerController
@RestController
@RequestMapping(“user”)
public class UserController {

  1. @Autowired
  2. private UserService userService;
  3. private static final Logger logger = LoggerFactory.getLogger(UserController.class);
  4. @RequestMapping("getById")
  5. public RestResponse<User> getUserById(Long id){
  6. User user = userService.getUserById(id);
  7. return RestResponse.success(user);
  8. }
  9. @RequestMapping("getList")
  10. public RestResponse<List<User>> getUserList(@RequestBody(required=false) User user){
  11. List<User> users = userService.getUserByQuery(user);
  12. return RestResponse.success(users);
  13. }