Spring Cloud杜绝循环依赖

zzhi.wang 2020-11-11 14:17:08
spring 循环 Cloud 依赖 杜绝


前言

大家在开发中有没有遇到过因循环依赖导致项目启动失败?在排查循环依赖的过程中有没困难?如何避免写出循环依赖的代码?

我没写过循环依赖的代码,作为稳定性负责人,我排查过多次。

有些逻辑简单的代码,循环依赖很容易排查。但是,我们的业务超级复杂,绝大多数循环依赖,一整天都查不出来。

起初我们遇到一个循环依赖处理一个,作为稳定性负责人,技术能干的事,不会让人做第二次,为此,我写了一段循环依赖巡检代码,把循环依赖扼杀在测试环境。

 

下面介绍下场景及处理思路,未必最优,欢迎交流。

背景

SpringCloud服务在上线时出现BeanCurrentlyInCreationException异常(服务本地启动无异常,测试环境启动也无异常,上线就偶尔异常)。

1,本地模拟如下:

Caused by: org.springframework.beans.factory.BeanCurrentlyInCreationException:
Error creating bean with name  'studentA' : Bean with name  'studentA'  has been injected into other beans [studentC] in its raw version as part of a circular reference, but has eventually been wrapped.
This means that said other beans  do  not use the  final  version of the bean.
This is often the result of over-eager type matching - consider using  'getBeanNamesOfType'  with the  'allowEagerInit'  flag turned off,  for  example.
 

2,生产场景如下图:

 

异常排查&模拟

 经过生产排查和本地测试,产生此异常的场景如下:

1,如果类方法有@Async注解,则可能出现如上异常

2,如果存在循环依赖,并且类方法上有@Async注解,则必然会出现如上异常。

1,场景演示:

 在spring中,基于field属性的循环依赖是可以的:

 

示例代码:

@Service
@Slf4j
public class StudentA {
@Autowired
private StudentB studentB;
public String test(){
return studentB.test();
}
public String test1(){
return "Studenta1";
}
}
@Slf4j
@Service
public class StudentB {
@Autowired
private StudentC studentC;
public String test() {
return "Studentb";
}
public String test1() {
return studentC.test1();
}
}
@Slf4j
@Service
public class StudentC {
@Autowired
private StudentA studentA;
public String test() {
return studentA.test();
}
public String test1() {
return "Studentc1";
}
}
@Autowired
private StudentA studentA ;
@Test
public void testA(){
String v= studentA.test();
log.info("testa={}",v);
}

以上代码输出正常

2,异常演示

如果我们的方法加上了@Async 注解。则抛出异常:

@Service
@Slf4j
public class StudentA {
@Autowired
private StudentB studentB;
@Async
public String test(){
return studentB.test();
}
@Async
public String test1(){
return "Studenta1";
}
}
@Slf4j
@Service
public class StudentB {
@Autowired
private StudentC studentC;
@Async
public String test() {
return "Studentb";
}
@Async
public String test1() {
return studentC.test1();
}
}
@Slf4j
@Service
public class StudentC {
@Autowired
private StudentA studentA;
@Async
public String test() {
return studentA.test();
}
@Async
public String test1() {
return "Studentc1";
}
}
@Autowired
private StudentA studentA ;
@Test
public void testA(){
String v= studentA.test();
log.info("testa={}",v);
}
Caused by: org.springframework.beans.factory.BeanCurrentlyInCreationException:
Error creating bean with name 'studentA': Bean with name 'studentA' has been injected into other beans [studentC] in its raw version as part of a circular reference, but has eventually been wrapped.
This means that said other beans do not use the final version of the bean.
This is often the result of over-eager type matching - consider using 'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.

3,解决异常

A,B,C三个类中,至少一个类的field 必须加@Lazy  

@Service
@Slf4j
public class StudentA {
@Autowired
@Lazy
private StudentB studentB;
@Async
public String test(){
return studentB.test();
}
@Async
public String test1(){
return "Studenta1";
}
}
@Slf4j
@Service
public class StudentB {
@Autowired
@Lazy
private StudentC studentC;
@Async
public String test() {
return "Studentb";
}
@Async
public String test1() {
return studentC.test1();
}
}
@Slf4j
@Service
public class StudentC {
@Autowired
@Lazy
private StudentA studentA;
@Async
public String test() {
return studentA.test();
}
@Async
public String test1() {
return "Studentc1";
}
}

参考 :https://my.oschina.net/tridays/blog/805111 

杜绝循环依赖的解决方案

这里根据我司的服务架构介绍一下如何避免循环依赖,我司用的spring cloud 全家桶,注册中心用的consul,配置中心有config 和apollo。

1,查看bean的依赖

spring-cloud 提供了bean信息查看功能,通过ip:端口+/actuator/beans可查看(如何配置actuator这里不详细讨论),如下图,我们可以看到每个bean依赖的bean
 

  

2,解析bean及其依赖beans

如上,我们可以查看某个bean的依赖项,由此,我们可以递归查找bean是否存在循环引用。

bean 信息模型

@Data
public class ApplicationBeans {
private Map<String, ContextBeans> contexts;
}
@Data
public class ContextBeans {
private Map<String, BeanDescriptor> beans;
private String parentId;
}

 

 3,代码实现

这里检测项目起名alarm-center,检测类为CheckCyclicDependenceService 

@Slf4j
@RefreshScope
@Service
public class CheckCyclicDependenceService {

// 服务发现 @Autowired
private DiscoveryClient discoveryClient;
//默认检测 api,admin两个项目,如果想检测其它项目,可在config配置 @Value(
"${check-serviceids-value:api,admin}") private String checkServiceIds;

//入口
public void checkCyclicDependence() { if (Strings.isNullOrEmpty(checkServiceIds)) { return; } List<String> serviceIds = Arrays.asList(checkServiceIds.split(",")); for (String serviceId : serviceIds) { long start = System.currentTimeMillis(); RestTemplate restTemplate = new RestTemplate();
//根据服务名去consul找一个服务实例 ServiceInstance instance
= discoveryClient.getInstances(serviceId).get(0); String url = instance.getUri() + "/actuator/beans"; //所有的beans信息 String applicationBeansStr = restTemplate.getForObject(url, String.class); ApplicationBeans applicationBeans = JSONObject.parseObject(applicationBeansStr, ApplicationBeans.class); long end = System.currentTimeMillis(); log.info("checkCyclicDependence get applicationBeans end,serviceid={},coust={}", serviceId, (end - start)); Map<String, ContextBeans> contexts = applicationBeans.getContexts(); Map<String, BeanDescriptor> qualifiedBeans = new HashMap<>(); for (Map.Entry<String, ContextBeans> conEntry : contexts.entrySet()) { if (!conEntry.getKey().startsWith(serviceId)) { continue; } ContextBeans contextBeans = conEntry.getValue(); Map<String, BeanDescriptor> beans = contextBeans.getBeans(); for (Map.Entry<String, BeanDescriptor> entry1 : beans.entrySet()) { String beanName = entry1.getKey().toLowerCase(); BeanDescriptor beanDescriptor = entry1.getValue(); if (!beanDescriptor.getType().startsWith("com.shuidihuzhu") || beanName.endsWith("aspect") || beanName.endsWith("controller") || beanName.endsWith("dao") || beanName.endsWith("datasource") || beanName.endsWith("fallback") || beanDescriptor.getDependencies().length == 0) { continue; } qualifiedBeans.put(entry1.getKey(), beanDescriptor); } } StringBuilder sb = new StringBuilder(); cyclicDependence(qualifiedBeans, sb); if (sb.length() > 0) { sb.append(System.getProperty("line.separator")); sb.append("重注代码质量,尽量做到无循环依赖"); sb.append(System.getProperty("line.separator")); sb.append("所属服务:" + serviceId); //alarmClient.sendByUser(Lists.newArrayList("zhangzhi"), sb.toString()); alarmClient.sendByGroup("cf-server-alarm", sb.toString()); end = System.currentTimeMillis(); } log.info("checkCyclicDependence end,serviceid={},coust={}", serviceId, (end - start)); } } public void cyclicDependence(Map<String, BeanDescriptor> beans, StringBuilder sb) { for (Map.Entry<String, BeanDescriptor> bean : beans.entrySet()) { String beanName = bean.getKey(); check(beans, beanName, beanName, 0, sb); } } public void check(Map<String, BeanDescriptor> beans, String beanName, String dependenceName, int depth, StringBuilder sb) { if (depth == 4) {//这里可以指定深度,层级过多,容易栈溢出 return; } depth++; BeanDescriptor bean = beans.get(dependenceName);//依赖项的依赖项 if (bean != null) { String[] deps = bean.getDependencies();//依赖项 for (String dep : deps) { if (dep.equals(beanName)) { sb.append(System.getProperty("line.separator")); String str = String.format("%s和%s存在循环依赖;", beanName, dependenceName); sb.append(str); log.info(str); } else { check(beans, beanName, dep, depth, sb); } } } } }

 

效果

我们在测试环境有个job 每隔几分钟巡检,有循环依赖就企业微信报警,这里截取一段日志,如下:

 

最后

水滴保险商城-架构组招java实习生

要求:
1、具备较强的编程基本功,熟练掌握JAVA编程语言,熟悉常用数据结构与算法。
2、了解常用的开源框架和开源服务(Spring,Netty,MySQL,Redis,Tomcat,Nginx 等)。
3、熟悉网络编程、多线程编程、分布式等优先。
4、阅读过spring家族源码优先,有技术博客优先,熟悉spring-cloud技术栈优先。
5、 做事积极主动,有较强的执行能力和和较好的沟通能力。

 

 

版权声明
本文为[zzhi.wang]所创,转载请带上原文链接,感谢
https://www.cnblogs.com/zhangzhi19861216/p/13958124.html

  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云