加入收藏 | 设为首页 | 会员中心 | 我要投稿 安卓应用网 (https://www.0791zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

详解如何使用Jersey客户端请求Spring Boot(RESTFul)服务

发布时间:2020-05-23 19:46:21 所属栏目:Java 来源:互联网
导读:本文介绍了使用Jersey客户端请求SpringBoot(RESTFul)服务,分享给大家,具体如下:

本文介绍了使用Jersey客户端请求Spring Boot(RESTFul)服务,分享给大家,具体如下:

Jersey客户端获取Client对象实例封装:

@Service("jerseyPoolingClient") 
public class JerseyPoolingClientFactoryBean implements FactoryBean<Client>,InitializingBean,DisposableBean{ 
   
  /** 
   * Client接口是REST客户端的基本接口,用于和REST服务器通信。Client被定义为一个重量级的对象,其内部管理着 
   * 客户端通信底层的各种对象,比如连接器,解析器等。因此,不推荐在应用中产生大量的的Client实例,这一点在开发中 
   * 需要特别小心,另外该接口要求其实例要有关闭连接的保障,否则会造成内存泄露 
   */ 
  private Client client; 
   
  /** 
   * 一个Client最大的连接数,默认为2000 
   */ 
  private int maxTotal = 2000; 
   
  /** 
   * 每路由的默认最大连接数 
   */ 
  private int defaultMaxPerRoute = 1000; 
   
  private ClientConfig clientConfig; 
   
  public JerseyPoolingClientFactoryBean() { 
  } 
   
  /** 
   * 带配置的构造函数 
   * @param clientConfig 
   */ 
  public JerseyPoolingClientFactoryBean(ClientConfig clientConfig) { 
    this.clientConfig = clientConfig; 
  } 
 
  public JerseyPoolingClientFactoryBean(int maxTotal,int defaultMaxPerRoute) { 
    this.maxTotal = maxTotal; 
    this.defaultMaxPerRoute = defaultMaxPerRoute; 
  } 
 
  /** 
   * attention: 
   * Details:容器销毁时,释放Client资源 
   * @author chhliu 
   */ 
  @Override 
  public void destroy() throws Exception { 
    this.client.close(); 
  } 
 
  /** 
   * 
   * attention: 
   * Details:以连接池的形式,来初始化Client对象 
   * @author chhliu 
   */ 
  @Override 
  public void afterPropertiesSet() throws Exception { 
    // 如果没有使用带ClientConfig的构造函数,则该类的实例为null,则使用默认的配置初始化 
    if(this.clientConfig == null){ 
      final ClientConfig clientConfig = new ClientConfig(); 
      // 连接池管理实例,该类是线程安全的,支持多并发操作 
      PoolingHttpClientConnectionManager pcm = new PoolingHttpClientConnectionManager(); 
      pcm.setMaxTotal(this.maxTotal); 
      pcm.setDefaultMaxPerRoute(this.defaultMaxPerRoute); 
       
      clientConfig.property(ApacheClientProperties.CONNECTION_MANAGER,pcm); 
      /* 
       * 在使用Jersey来请求Spring Boot服务时,Spring Boot默认使用Jackson来解析JSON 
       * 而Jersey默认使用MOXy解析JSON,当Jersey Client想Spring Boot服务请求资源时, 
       * 这个差异会导致服务端和客户端对POJO的转换不同,造成反序列化的错误 
       * 因此,此处需要在Client的Config实例中注册Jackson特性 
       */ 
      clientConfig.register(JacksonFeature.class); 
      // 使用配置Apache连接器,默认连接器为HttpUrlConnector 
      clientConfig.connectorProvider(new ApacheConnectorProvider()); 
      client = ClientBuilder.newClient(clientConfig); 
    }else{ 
      // 使用构造函数中的ClientConfig来初始化Client对象 
      client = ClientBuilder.newClient(this.clientConfig); 
    } 
  } 
 
  /** 
   * attention: 
   * Details:返回Client对象,如果该对象为null,则创建一个默认的Client 
   * @author chhliu 
   */ 
  @Override 
  public Client getObject() throws Exception { 
    if(null == this.client){ 
      return ClientBuilder.newClient(); 
    } 
    return this.client; 
  } 
 
  /** 
   * attention: 
   * Details:获取Client对象的类型 
   * @author chhliu 
   */ 
  @Override 
  public Class<?> getObjectType() { 
    return (this.client == null ? Client.class : this.client.getClass()); 
  } 
 
  /** 
   * attention: 
   * Details:Client对象是否为单例,默认为单例 
   * @author chhliu 
   */ 
  @Override 
  public boolean isSingleton() { 
    return true; 
  } 
} 

请求Spring Boot服务的封装:

@Component("jerseyClient") 
public class JerseyClient { 
   
  @Resource(name="jerseyPoolingClient") 
  private Client client; 
   
  /** 
   * attention: 
   * Details:通过id来查询对象 
   * @author chhliu 
   */ 
  public ResultMsg<GitHubEntity> getResponseById(final String id) throws JsonProcessingException,IOException{ 
    WebTarget webTarget = client.target("http://localhost:8080").path("/github/get/user/"+id); 
    Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON); 
    GenericType<ResultMsg<GitHubEntity>> genericType = new GenericType<ResultMsg<GitHubEntity>>(){}; 
    Response response = invocationBuilder.get(); 
    if(response.getStatus() == 200){ 
      /* 
       * 当调用readEntity方法时,程序会自动的释放连接 
       * 即使没有调用readEntity方法,直接返回泛型类型的对象,底层仍然会释放连接 
       */ 
      return response.readEntity(genericType); 
    }else{ 
      ResultMsg<GitHubEntity> res = new ResultMsg<GitHubEntity>(); 
      res.setErrorCode(String.valueOf(response.getStatus())); 
      res.setErrorMsg(response.getStatusInfo().toString()); 
      res.setOK(false); 
      return res; 
    } 
  } 
   
  /** 
   * attention: 
   * Details:分页查询 
   * @author chhliu 
   */ 
  public ResultMsg<Pager<GitHubEntity>> getGithubWithPager(final Integer pageOffset,final Integer pageSize,final String orderColumn){ 
    WebTarget webTarget = client.target("http://localhost:8080").path("/github/get/users/page") 
        .queryParam("pageOffset",pageOffset) 
        .queryParam("pageSize",pageSize) 
        .queryParam("orderColumn",orderColumn); 
        // 注意,如果此处的媒体类型为MediaType.APPLICATION_JSON,那么对应的服务中的参数前需加上@RequestBody 
        Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON); 
    GenericType<ResultMsg<Pager<GitHubEntity>>> genericType = new GenericType<ResultMsg<Pager<GitHubEntity>>>(){}; 
    Response response = invocationBuilder.get(); 
    if(response.getStatus() == 200){ 
      return response.readEntity(genericType); 
    }else{ 
      ResultMsg<Pager<GitHubEntity>> res = new ResultMsg<Pager<GitHubEntity>>(); 
      res.setErrorCode(String.valueOf(response.getStatus())); 
      res.setErrorMsg(response.getStatusInfo().toString()); 
      res.setOK(false); 
      return res; 
    } 
     
  } 
   
  /** 
   * attention: 
   * Details:根据用户名来查询 
   * @author chhliu 
   */ 
  public ResultMsg<List<GitHubEntity>> getResponseByUsername(final String username) throws JsonProcessingException,IOException{ 
    WebTarget webTarget = client.target("http://localhost:8080").path("/github/get/users/"+username); 
    Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON); 
    GenericType<ResultMsg<List<GitHubEntity>>> genericType = new GenericType<ResultMsg<List<GitHubEntity>>>(){}; 
    Response response = invocationBuilder.get(); 
    if(response.getStatus() == 200){ 
      return response.readEntity(genericType); 
    }else{ 
      ResultMsg<List<GitHubEntity>> res = new ResultMsg<List<GitHubEntity>>(); 
      res.setErrorCode(String.valueOf(response.getStatus())); 
      res.setErrorMsg(response.getStatusInfo().toString()); 
      res.setOK(false); 
      return res; 
    } 
  } 
   
  /** 
   * attention: 
   * Details:根据id来删除一个记录 
   * @author chhliu 
   */ 
  public ResultMsg<GitHubEntity> deleteById(final String id) throws JsonProcessingException,IOException{ 
    WebTarget target = client.target("http://localhost:8080").path("/github/delete/"+id); 
    GenericType<ResultMsg<GitHubEntity>> genericType = new GenericType<ResultMsg<GitHubEntity>>(){}; 
    Response response = target.request().delete(); 
    if(response.getStatus() == 200){ 
      return response.readEntity(genericType); 
    }else{ 
      ResultMsg<GitHubEntity> res = new ResultMsg<GitHubEntity>(); 
      res.setErrorCode(String.valueOf(response.getStatus())); 
      res.setErrorMsg(response.getStatusInfo().toString()); 
      res.setOK(false); 
      return res; 
    } 
  } 
   
  /** 
   * attention: 
   * Details:更新一条记录 
   * @author chhliu 
   */ 
  public ResultMsg<GitHubEntity> update(final GitHubEntity entity) throws JsonProcessingException,IOException{ 
    WebTarget target = client.target("http://localhost:8080").path("/github/put"); 
    GenericType<ResultMsg<GitHubEntity>> genericType = new GenericType<ResultMsg<GitHubEntity>>(){}; 
    Response response = target.request().buildPut(Entity.entity(entity,MediaType.APPLICATION_JSON)).invoke(); 
    if(response.getStatus() == 200){ 
      return response.readEntity(genericType); 
    }else{ 
      ResultMsg<GitHubEntity> res = new ResultMsg<GitHubEntity>(); 
      res.setErrorCode(String.valueOf(response.getStatus())); 
      res.setErrorMsg(response.getStatusInfo().toString()); 
      res.setOK(false); 
      return res; 
    } 
  } 
   
  /** 
   * attention: 
   * Details:插入一条记录 
   * @author chhliu 
   */ 
  public ResultMsg<GitHubEntity> save(final GitHubEntity entity) throws JsonProcessingException,IOException{  
     WebTarget target = client.target("http://localhost:8080").path("/github/post"); 
     GenericType<ResultMsg<GitHubEntity>> genericType = new GenericType<ResultMsg<GitHubEntity>>(){}; 
     Response response = target.request().buildPost(Entity.entity(entity,MediaType.APPLICATION_JSON)).invoke(); 
     if(response.getStatus() == 200){ 
       return response.readEntity(genericType); 
     }else{ 
      ResultMsg<GitHubEntity> res = new ResultMsg<GitHubEntity>(); 
      res.setErrorCode(String.valueOf(response.getStatus())); 
      res.setErrorMsg(response.getStatusInfo().toString()); 
      res.setOK(false); 
      return res; 
     } 
  } 
} 

Jersey客户端接口详解

1 Client接口

(编辑:安卓应用网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读