Spring cloud eliminates circular dependency

zzhi.wang 2020-11-11 14:17:08
spring cloud eliminates circular dependency


Preface

Have you ever encountered project startup failure due to cyclic dependency in development ? Are there any difficulties in the process of troubleshooting circular dependencies ? How to avoid writing loop dependent code ?

I haven't written code for circular dependencies , As head of stability , I've checked many times .

Some simple logic code , Cyclic dependencies are easy to check . however , Our business is super complex , The vast majority of circular dependencies , I couldn't find out all day .

At first we came across a circular dependency dealing with a , As head of stability , What technology can do , It won't make people do it a second time , So , I wrote a circular dependency patrol code , Kill the cyclic dependency in the test environment .

 

The following is the scene and processing ideas , Not necessarily the best , Welcome to exchange .

background

SpringCloud When the service comes online BeanCurrentlyInCreationException abnormal ( There is no exception when the service is started locally , The test environment starts without exception , Sometimes it's abnormal when you go online ).

1, The local simulation is as follows :

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, The production scenario is shown in the figure below :

 

Troubleshooting & simulation

  After production screening and local testing , The scenario in which this exception occurs is as follows :

1, If the class method has @Async annotation , The above exception may occur

2, If there is a circular dependency , And class methods have @Async annotation , It is inevitable that the above abnormalities will occur .

1, Scene demonstration :

  stay spring in , be based on field The circular dependency of attributes is OK :

 

Sample code :

@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);
}

The above code output is normal

2, Exception demonstration

If our approach adds @Async annotation . Throw an exception :

@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, Solve the exception

A,B,C Of the three classes , Of at least one class field Must be added @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";
}
}

Reference resources :https://my.oschina.net/tridays/blog/805111 

Solutions to eliminate circular dependencies

Here, according to our service architecture, we will introduce how to avoid circular dependence , We use spring cloud Family bucket , The registry uses consul, The configuration center has config and apollo.

1, see bean Dependence

spring-cloud Provides bean Information viewing function , adopt ip: port +/actuator/beans You can see ( How to configure actuator It's not discussed in detail here ), Here's the picture , We can see each one bean Rely on the bean
 

  

2, analysis bean And its dependence beans

Above , We can look at some bean The dependencies of , thus , We can recursively find bean Whether there is a circular reference .

bean Information model

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

 

 3, Code implementation

Here the test item is named alarm-center, The detection class is CheckCyclicDependenceService 

@Slf4j
@RefreshScope
@Service
public class CheckCyclicDependenceService {

// Service discovery @Autowired
private DiscoveryClient discoveryClient;
// Default detection api,admin Two projects , If you want to test other items , Can be found in config To configure @Value(
"${check-serviceids-value:api,admin}") private String checkServiceIds;

// entrance
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();
// According to the service name consul Find a service instance ServiceInstance instance
= discoveryClient.getInstances(serviceId).get(0); String url = instance.getUri() + "/actuator/beans"; // be-all beans Information 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(" Re note code quality , Try to be non cyclic "); sb.append(System.getProperty("line.separator")); sb.append(" Services :" + 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) {// Here you can specify the depth , Too many levels , Easy stack overflow return; } depth++; BeanDescriptor bean = beans.get(dependenceName);// Dependencies of dependencies if (bean != null) { String[] deps = bean.getDependencies();// Dependencies for (String dep : deps) { if (dep.equals(beanName)) { sb.append(System.getProperty("line.separator")); String str = String.format("%s and %s There is a cyclic dependency ;", beanName, dependenceName); sb.append(str); log.info(str); } else { check(beans, beanName, dep, depth, sb); } } } } }

 

effect

We have a test environment job Patrol every few minutes , There is a circular dependence on the enterprise wechat alarm , Here we intercept a log , as follows :

 

Last

Drop insurance Mall - Architecture group recruitment java The intern

requirement :
1、 Have strong basic programming skills , Have a good command of JAVA programing language , Familiar with common data structures and algorithms .
2、 Learn about common open source frameworks and services (Spring,Netty,MySQL,Redis,Tomcat,Nginx etc. ).
3、 Familiar with network programming 、 Multithreaded programming 、 Distributed and so on .
4、 Read over spring Family source code priority , Technical blogs are preferred , be familiar with spring-cloud Technology stack first .
5、 Be proactive , Have strong executive ability and good communication ability .

 

 

版权声明
本文为[zzhi.wang]所创,转载请带上原文链接,感谢

  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课程百度云