springmvc--spring的resttemplate - Go语言中文社区

springmvc--spring的resttemplate


目录

json序列化

反序列化  (对象)

序列化 (对象)

反序列化 json-->obj  (集合List)

序列化(集合List)

jsonUtils

Spring的Restemplate

负载均衡的算法

Hystrix熔断配置

Feign客户端(里面集成了Rabbit负载均衡和Hystrix熔断器)


json序列化

ObjectMapper类:

ObjectMapper mapper = new ObjectMapper();

反序列化  (对象)

Api    xxx xx=mapper.readValue(json,xxx.class)  

序列化 (对象)

String json = mapper.waiteValueAsString(xxx);

反序列化 json-->obj  (集合List<xxx>)

List<xxx> xxxs= new List<xxx >;

List<User> us = mapper.readValue(json, new TypeReference<Lsit<User>>(){})

序列化(集合List<xxx>)

String json = mapper.waiteValueAsString(xxxs);

 

 

 

jsonUtils

package com.leyou.common.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.lang.Nullable;

import java.io.IOException;
import java.util.List;
import java.util.Map;


public class JsonUtils {

    public static final ObjectMapper mapper = new ObjectMapper();

    private static final Logger logger = LoggerFactory.getLogger(JsonUtils.class);

    @Nullable
    public static String serialize(Object obj) {
        if (obj == null) {
            return null;
        }
        if (obj.getClass() == String.class) {
            return (String) obj;
        }
        try {
            return mapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            logger.error("json序列化出错:" + obj, e);
            return null;
        }
    }

    @Nullable
    public static <T> T parse(String json, Class<T> tClass) {
        try {
            return mapper.readValue(json, tClass);
        } catch (IOException e) {
            logger.error("json解析出错:" + json, e);
            return null;
        }
    }

    @Nullable
    public static <E> List<E> parseList(String json, Class<E> eClass) {
        try {
            return mapper.readValue(json, mapper.getTypeFactory().constructCollectionType(List.class, eClass));
        } catch (IOException e) {
            logger.error("json解析出错:" + json, e);
            return null;
        }
    }

    @Nullable
    public static <K, V> Map<K, V> parseMap(String json, Class<K> kClass, Class<V> vClass) {
        try {
            return mapper.readValue(json, mapper.getTypeFactory().constructMapType(Map.class, kClass, vClass));
        } catch (IOException e) {
            logger.error("json解析出错:" + json, e);
            return null;
        }
    }

    @Nullable
    public static <T> T nativeRead(String json, TypeReference<T> type) {
        try {
            return mapper.readValue(json, type);
        } catch (IOException e) {
            logger.error("json解析出错:" + json, e);
            return null;
        }
    }
}

Spring的Restemplate

简化rest风格的开发底层Http

在SpringBoot启动类进行一个注册 

@Bean

public RestTemplate  restTemplate  (){

return  new RestTemplate(new OkHttp3ClientHttpRequestFactory());

 }

使用 直接@Autowired注入

private ResTemplate  resTemplate;

调用  getForObject()方法 底层自动转json

resTemplate.getForObject("url地址",xxx.class)

 

通过Eureka 提供的  DisCoveryClient disCoveryClient优化代码 ; 动态获取服务的url

通过注册在Eureka的服务名称获取服务的实例信息集合列表

private static Integer pos= 0;
pubcli xxx  xxx(){
List<serviceInstance> instances= disCoveryClient .getinstances("Eureka服务id");

//负载均衡分发服务 通过pos来指定服务的分发

serviceInstance host= instances.getHost(pos%instances.size()/*之间的数据*/);

int port =  instances.getPort();

string url = "http://"+host+":"+port+"/xxx/"+参数

//设置一个点
if(pos==10000){
  pos=0;
}

pos++;

 return this.resTemplate.getForObject(url ,xxx.class);


}

负载均衡的算法

使用Ribbit框架实现负载均衡再次优化代码

使用方式在springBoot启动类开启Ribbit注解默认策略是轮询

    @Bean
    @LoadBalanced
    public RestTemplate  restTemplate(){
         RestTemplate restTemplate = new RestTemplate(new 
                      OkHttp3ClientHttpRequestFactory());                
         return restTemplate;
    }
 
//private static Integer pos= 0;
pubcli xxx   xxx(){
//List<serviceInstance> instances= disCoveryClient .getinstances("Eureka服务id");

//负载均衡分发服务 通过pos来指定服务的分发

//serviceInstance host= instances.getHost(pos%instances.size()/*之间的数据*/);

//int port =  instances.getPort();

string url = "http://服务id/xxx/"+参数

 
return  this.resTemplate.getForObject(url ,xxx.class);

}

改变负载均衡策略

yml文件设置提供了入口在服务的消费方配置

user-service:
  ribbon:
    NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule

格式是:{服务名称}.ribbon.NFLoadBalancerRuleClassName,值就是IRule的实现类。

Hystrix熔断配置

在启动类上开启熔断  

@EnableHystrix

在调用的方法上加上注解

@HystrixCommand(fallbackMethod="回滚出错的方法名")

Feign客户端(里面集成了Rabbit负载均衡和Hystrix熔断器)

使用Feign客户端继续最后优化上面代码

  • 第一步:在服务消费方引入 Spring-cloud-start-openfeign 依赖
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>

 

 

  • 第二步在启动类上开启fegin客户端
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class SearchApplication {

    public static void main(String[] args) {
        SpringApplication.run(SearchApplication.class, args);

    }
}
  • 第三步,编写一个接口
/**
 * value 服务id   path  后面跟的路径名  fallback  指定熔断回滚类
 */
@FeignClient(value="item-service",path = "路径名",fallback=SpecificationFallback.class)
public interface SpecificationClient  {

   /**
    * 请求方式   占位符(参数)   方法名称
   */
     @GetMapping("/{id}")
     xxx  queryById(@Pathvariable("id") Long id);
   
}
  • 第四步在消费者yml里面配置熔断机制
hystrix:
  command:
    default:
      execution:
        isolation:
          thread:
            timeoutInMilliseconds: 1500 # Hsytrix的超时时间,默认1500毫秒
feign:
  hystrix:
    enabled: true # 开启Feign的熔断功能
  • 第五步配置熔断
@Componet
public class SpecificationFallback  implements  SpecificationClient{

    //重写接口中的方法
    @Override
    public User queryById(Long id){
        return null;
    } 

}
  • 第六步Feign的请求压缩

我们也可以对请求的数据类型,以及触发压缩的大小下限进行设置:

feign:
  compression:
    request:
      enabled: true # 开启请求压缩
      mime-types: text/html,application/xml,application/json # 设置压缩的数据类型
      min-request-size: 2048 # 设置触发压缩的大小下限
  • 第七步Fegin的日志输出

1)调整日志级别为debug

logging:
  level:
    cn.itcast: debug

2)编写配置类,定义日志级别

@Configuration
public class FeignConfig {
    @Bean
    Logger.Level feignLoggerLevel(){
        return Logger.Level.FULL;
    }
}
  • NONE:不记录任何日志信息,这是默认值。

  • BASIC:仅记录请求的方法,URL以及响应状态码和执行时间

  • HEADERS:在BASIC的基础上,额外记录了请求和响应的头信息

  • FULL:记录所有请求和响应的明细,包括头信息、请求体、元数据。

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/adminBfl/article/details/82723591
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2020-03-01 22:50:16
  • 阅读 ( 1255 )
  • 分类:

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢