二次封装RestTemplate实现个人页展示

 

 

二次封装RestTemplate实现个人页展示

 

 

Rests

package com.mooc.house.api.utils;

import java.util.concurrent.Callable;

import org.apache.commons.lang3.reflect.FieldUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public final class Rests {
  
  private static final Logger LOGGER = LoggerFactory.getLogger(Rests.class);
  
  private Rests(){};
  
  private static DefaultHanlder defaultHanlder = new DefaultHanlder();
  
  
  /**
   * 执行服务调用,并判断返回状态
   * @param callable
   * @return
   */
  public static  T exc(Callable callable){
    return exc(callable, defaultHanlder);
  }
  
  public static  T exc(Callable callable,ResultHandler handler){
    T result = sendReq(callable);
    return handler.handle(result);
  }
  
  public static String toUrl(String serviceName,String path){
    return "http://" + serviceName + path;
  }
  
  public static class DefaultHanlder implements ResultHandler {

    @Override
    public  T handle(T result) {
      int code = 1;
      String msg = "";
      try {
        code =  (Integer)FieldUtils.readDeclaredField(result, "code", true);
        msg =  (String)FieldUtils.readDeclaredField(result, "msg", true);
      } catch (Exception e) {
        //ignore
      }
      if (code != 0) {
        throw new RestException("Get erroNo " + code + " when execute rest call with errorMsg " +msg);
      }
      return result;
    }
    
  }
  
  public interface ResultHandler{
     T handle(T result);
  }

  public static  T sendReq(Callable callable){
    T result = null;
    try {
      result = callable.call();
    } catch (Exception e) {
      throw new RestException("sendReq error by " + e.getMessage());
    }finally {
      LOGGER.info("result={}",result);
    }
    return result;
    
  }
  
  
}

 

 

 

 

封装前后调用用户服务对比

  /**
   * 调用鉴权服务
   * @param token
   * @return
   */
  @HystrixCommand(fallbackMethod="getUserByTokenFb")
  public User getUserByToken(String token) {
    String url = "http://" + userServiceName + "/user/get?token=" + token;
    ResponseEntity> responseEntity = rest.get(url, new ParameterizedTypeReference>() {});
    RestResponse response = responseEntity.getBody();
    if (response == null || response.getCode() != 0) {
       return null;
    }
    return response.getResult();
  }

  @HystrixCommand
  public List getAllAgency() {
    return Rests.exc(() ->{
      String url = Rests.toUrl(userServiceName, "/agency/list");
      ResponseEntity>> responseEntity =
          rest.get(url, new ParameterizedTypeReference>>() {});
      return responseEntity.getBody();
    }).getResult();
  } 

 

 

 

 


==============================
QQ群:143522604
群里有相关资源
欢迎和大家一起学习、交流、提升!
==============================

 

 

 

 

 

 

 

 

 

 

你可能感兴趣的:(【微服务项目】,【项目】)