目录
json序列化
反序列化 (对象)
序列化 (对象)
反序列化 json-->obj (集合List)
序列化(集合List)
jsonUtils
Spring的Restemplate
负载均衡的算法
Hystrix熔断配置
Feign客户端(里面集成了Rabbit负载均衡和Hystrix熔断器)
ObjectMapper类:
ObjectMapper mapper = new ObjectMapper();
Api xxx xx=mapper.readValue(json,xxx.class)
String json = mapper.waiteValueAsString(xxx);
List
List
String json = mapper.waiteValueAsString(xxxs);
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 parse(String json, Class tClass) {
try {
return mapper.readValue(json, tClass);
} catch (IOException e) {
logger.error("json解析出错:" + json, e);
return null;
}
}
@Nullable
public static List parseList(String json, Class 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 Map parseMap(String json, Class kClass, Class 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 nativeRead(String json, TypeReference type) {
try {
return mapper.readValue(json, type);
} catch (IOException e) {
logger.error("json解析出错:" + json, e);
return null;
}
}
}
简化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 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 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的实现类。
在启动类上开启熔断
@EnableHystrix
在调用的方法上加上注解
@HystrixCommand(fallbackMethod="回滚出错的方法名")
使用Feign客户端继续最后优化上面代码
org.springframework.cloud
spring-cloud-starter-openfeign
@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);
}
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:
compression:
request:
enabled: true # 开启请求压缩
mime-types: text/html,application/xml,application/json # 设置压缩的数据类型
min-request-size: 2048 # 设置触发压缩的大小下限
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:记录所有请求和响应的明细,包括头信息、请求体、元数据。