前言
最近在学习dubbo相关内容,在整合Hystrix时,因为与springboot版本不兼容,踩了很多坑,干脆就直接新建一个测试项目,顺便回顾下Springboot + Dubbo + Hystrix整合过程。
提示:本人小白一枚,若有错误请提出。
1.创建工程项目
● 父工程 ------- maven项目
● 接口模块------- maven项目
● 提供者模块------- springboot项目
● 消费者模块------- springboot项目
2.创建接口模块
创建两个service接口
public interface UserService {
/**
* 获取用户地址
* @return
*/
public String getUserAddressList();
}
public interface OrderService {
/**
* 初始化订单
*/
public void initOrder();
}
3.创建提供者模块
3.1 导入相关依赖包
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.1.RELEASE</version>
<relativePath/><!-- lookup parent from repository -->
</parent>
<groupId>com.sunl</groupId>
<artifactId>boot-user-service-provider</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>boot-user-service-provider</name>
<description>boot-user-service-provider</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--导入接口层-->
<dependency>
<groupId>com.sunl</groupId>
<artifactId>boot-interface-api</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<!--hystrix集成依赖-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
<version>2.0.3.RELEASE</version>
</dependency>
<!--Dubbo集成SpringBoot起步依赖-->
<dependency>
<groupId>com.alibaba.spring.boot</groupId>
<artifactId>dubbo-spring-boot-starter</artifactId>
<version>2.0.0</version>
</dependency>
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>3.8.0</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.101tec</groupId>
<artifactId>zkclient</artifactId>
<version>0.11</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
spring-boot-starter-parent与spring-cloud-starter-netflix-hystrix要相互兼容,否则会报错
Caused by: java.lang.ClassNotFoundException:
org.springframework.boot.context.properties.ConfigurationBeanFactoryMetadata
3.2 创建用户服务接口实现类
/**
* 暴露服务
* @author HP
*/
@Service
@Component
public class UserServiceImpl implements UserService {
/**
* 按照用户id返回所有的收货地址
* @HystrixCommand 注解是方法级别的,在你需要捕获的方法上加上注解
* fallbackMethod:标记的是捕获异常时需要执行的方法,方法名称跟value值要一样
* @return
*/
@HystrixCommand
@Override
public String getUserAddressList() {
System.out.println("==============UserServiceImpl......20883=================");
double num = Math.random();
System.out.println(num);
if (num > 0.5){
throw new RuntimeException();
}
return "获取到数字 " + num;
}
}
@Service(version = “1.0.0”, retries = 2)引用的是阿里巴巴的依赖 import
com.alibaba.dubbo.config.annotation.Service;
fallbackMethod:标记的是捕获异常时需要执行的方法,方法名称跟value值要一样
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'configurationPropertiesBeans' defined in class path resource [org/springframework/cloud/autoconfigure/ConfigurationPropertiesRebinderAutoConfiguration.class]: Post-processing of merged bean definition failed; nested exception is java.lang.IllegalStateException: Failed to introspect Class [org.springframework.cloud.context.properties.ConfigurationPropertiesBeans] from ClassLoader [sun.misc.Launcher$AppClassLoader@18b4aac2]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:597) ~[spring-beans-5.3.19.jar:5.3.19]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542) ~[spring-beans-5.3.19.jar:5.3.19]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.19.jar:5.3.19]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.19.jar:5.3.19]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.19.jar:5.3.19]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:213) ~[spring-beans-5.3.19.jar:5.3.19]
at org.springframework.context.support.PostProcessorRegistrationDelegate.registerBeanPostProcessors(PostProcessorRegistrationDelegate.java:270) ~[spring-context-5.3.19.jar:5.3.19]
at org.springframework.context.support.AbstractApplicationContext.registerBeanPostProcessors(AbstractApplicationContext.java:762) ~[spring-context-5.3.19.jar:5.3.19]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:567) ~[spring-context-5.3.19.jar:5.3.19]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:740) [spring-boot-2.6.7.jar:2.6.7]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:415) [spring-boot-2.6.7.jar:2.6.7]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:303) [spring-boot-2.6.7.jar:2.6.7]
at org.springframework.boot.builder.SpringApplicationBuilder.run(SpringApplicationBuilder.java:164) ~[spring-boot-2.6.7.jar:2.6.7]
at org.springframework.cloud.bootstrap.BootstrapApplicationListener.bootstrapServiceContext(BootstrapApplicationListener.java:212) ~[spring-cloud-context-2.2.9.RELEASE.jar:2.2.9.RELEASE]
at org.springframework.cloud.bootstrap.BootstrapApplicationListener.onApplicationEvent(BootstrapApplicationListener.java:117) ~[spring-cloud-context-2.2.9.RELEASE.jar:2.2.9.RELEASE]
at org.springframework.cloud.bootstrap.BootstrapApplicationListener.onApplicationEvent(BootstrapApplicationListener.java:74) ~[spring-cloud-context-2.2.9.RELEASE.jar:2.2.9.RELEASE]
at org.springframework.context.event.SimpleApplicationEventMulticaster.doInvokeListener(SimpleApplicationEventMulticaster.java:176) ~[spring-context-5.3.19.jar:5.3.19]
at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:169) ~[spring-context-5.3.19.jar:5.3.19]
at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:143) ~[spring-context-5.3.19.jar:5.3.19]
at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:131) ~[spring-context-5.3.19.jar:5.3.19]
at org.springframework.boot.context.event.EventPublishingRunListener.environmentPrepared(EventPublishingRunListener.java:85) ~[spring-boot-2.6.7.jar:2.6.7]
at org.springframework.boot.SpringApplicationRunListeners.lambda$environmentPrepared$2(SpringApplicationRunListeners.java:66) ~[spring-boot-2.6.7.jar:2.6.7]
at java.util.ArrayList.forEach(ArrayList.java:1249) ~[na:1.8.0_92]
at org.springframework.boot.SpringApplicationRunListeners.doWithListeners(SpringApplicationRunListeners.java:120) ~[spring-boot-2.6.7.jar:2.6.7]
at org.springframework.boot.SpringApplicationRunListeners.doWithListeners(SpringApplicationRunListeners.java:114) ~[spring-boot-2.6.7.jar:2.6.7]
at org.springframework.boot.SpringApplicationRunListeners.environmentPrepared(SpringApplicationRunListeners.java:65) ~[spring-boot-2.6.7.jar:2.6.7]
at org.springframework.boot.SpringApplication.prepareEnvironment(SpringApplication.java:339) [spring-boot-2.6.7.jar:2.6.7]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:297) [spring-boot-2.6.7.jar:2.6.7]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1312) [spring-boot-2.6.7.jar:2.6.7]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1301) [spring-boot-2.6.7.jar:2.6.7]
at com.sunl.dubbo.BootUserServiceProviderApplication.main(BootUserServiceProviderApplication.java:19) [classes/:na]
Caused by: java.lang.IllegalStateException: Failed to introspect Class [org.springframework.cloud.context.properties.ConfigurationPropertiesBeans] from ClassLoader [sun.misc.Launcher$AppClassLoader@18b4aac2]
at org.springframework.util.ReflectionUtils.getDeclaredMethods(ReflectionUtils.java:485) ~[spring-core-5.3.19.jar:5.3.19]
at org.springframework.util.ReflectionUtils.doWithLocalMethods(ReflectionUtils.java:321) ~[spring-core-5.3.19.jar:5.3.19]
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.buildLifecycleMetadata(InitDestroyAnnotationBeanPostProcessor.java:232) ~[spring-beans-5.3.19.jar:5.3.19]
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.findLifecycleMetadata(InitDestroyAnnotationBeanPostProcessor.java:210) ~[spring-beans-5.3.19.jar:5.3.19]
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessMergedBeanDefinition(InitDestroyAnnotationBeanPostProcessor.java:149) ~[spring-beans-5.3.19.jar:5.3.19]
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessMergedBeanDefinition(CommonAnnotationBeanPostProcessor.java:305) ~[spring-context-5.3.19.jar:5.3.19]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyMergedBeanDefinitionPostProcessors(AbstractAutowireCapableBeanFactory.java:1116) ~[spring-beans-5.3.19.jar:5.3.19]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:594) ~[spring-beans-5.3.19.jar:5.3.19]
... 30 common frames omitted
Caused by: java.lang.NoClassDefFoundError: org/springframework/boot/context/properties/ConfigurationBeanFactoryMetadata
at java.lang.Class.getDeclaredMethods0(Native Method) ~[na:1.8.0_92]
at java.lang.Class.privateGetDeclaredMethods(Class.java:2701) ~[na:1.8.0_92]
at java.lang.Class.getDeclaredMethods(Class.java:1975) ~[na:1.8.0_92]
at org.springframework.util.ReflectionUtils.getDeclaredMethods(ReflectionUtils.java:467) ~[spring-core-5.3.19.jar:5.3.19]
... 37 common frames omitted
Caused by: java.lang.ClassNotFoundException: org.springframework.boot.context.properties.ConfigurationBeanFactoryMetadata
at java.net.URLClassLoader.findClass(URLClassLoader.java:381) ~[na:1.8.0_92]
at java.lang.ClassLoader.loadClass(ClassLoader.java:424) ~[na:1.8.0_92]
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331) ~[na:1.8.0_92]
at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ~[na:1.8.0_92]
... 41 common frames omitted
Process finished with exit code 1
3.3 配置文件配置属性
#配置端口
server.port=8082
#表示当前应用的名字,必须指定一个唯一的名称
dubbo.application.name=boot-user-service-provider
#注册中心地址
dubbo.registry.address=zookeeper://localhost:2181
dubbo.registry.protocol=zookeeper
#配置协议和端口 (默认是20880,修改端口,不同的服务提供者端口不能重复)
dubbo.protocol.name=dubbo
dubbo.protocol.port=20880
此处配置,最后改成了spring容器托管
package com.sunl.dubbo.config;
import com.alibaba.dubbo.config.*;
import com.sunl.dubbo.service.UserService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.ArrayList;
/**
* @program: dubbo
* @description: 服务提供者配置类
* @author: Sunl
* @create: 2022-05-08 13:12
**/
@Configuration
public class MyDubboConfig {
/**
* 1.指定当前服务/应用的名字(同样的服务名字相同,不要和别的服务同名
* <dubbo:application name="user-service-provider"/>
* @return
*/
@Bean
public ApplicationConfig applicationConfig(){
ApplicationConfig applicationConfig = new ApplicationConfig();
applicationConfig.setName("boot-user-service-provider");
applicationConfig.setId("boot-user-service-provider");
return applicationConfig;
}
/**
* 2.指定注册中心的位置
* <dubbo:registry protocol="zookeeper" address="127.0.0.1:2181"/>
* @return
*/
@Bean
public RegistryConfig registryConfig(){
RegistryConfig registryConfig = new RegistryConfig();
registryConfig.setProtocol("zookeeper");
registryConfig.setAddress("127.0.0.1:2181");
return registryConfig;
}
/**
* 3.指定通信规则(通信协议?通信端口)
* <dubbo:protocol name="dubbo" port="20890"/>
* @return
*/
@Bean
public ProtocolConfig protocolConfig(){
ProtocolConfig protocolConfig = new ProtocolConfig();
protocolConfig.setName("dubbo");
protocolConfig.setPort(20883);
return protocolConfig;
}
/**
* 4.暴露服务 ref:指向服务的真正的实现对象
* <dubbo:service interface="com.sun.gmall.service.UserService"
* ref="userServiceImpl01"
* timeout="1000"
* version="1.0.0"
* >
* <dubbo:method name="getUserAddressList" timeout="1000"/>
* </dubbo:service>
* <bean id="userServiceImpl01" class="com.sun.gmall.service.impl.UserServiceImpl"/>
* @return
*/
@Bean
public ServiceConfig<UserService> serviceConfig(UserService userService){
ServiceConfig<UserService> serviceConfig = new ServiceConfig<>();
/*serviceConfig.setInterface("com.sun.gmall.service.UserService");*/
serviceConfig.setInterface(UserService.class);
serviceConfig.setRef(userService);
serviceConfig.setTimeout(1000);
serviceConfig.setVersion("1.0.0");
/*配置每一个method信息*/
MethodConfig methodConfig = new MethodConfig();
methodConfig.setName("getUserAddressList");
methodConfig.setTimeout(1000);
//将method设置关联到service配置中
ArrayList<MethodConfig> methods = new ArrayList<>();
methods.add(methodConfig);
serviceConfig.setMethods(methods);
return serviceConfig;
}
}
3.4 配置启动类,并启动
/**
* @author HP
* @EnableDubbo 开启dubbo支持
* @EnableHystrix 开启服务容错
*/
@EnableDubbo
@EnableHystrix
@SpringBootApplication
public class BootUserServiceProviderApplication {
public static void main(String[] args) {
SpringApplication.run(BootUserServiceProviderApplication.class, args);
}
}
打开http://localhost:7001/确认提供者服务打开
4.创建消费者模块
4.1 导入相关依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.1.RELEASE</version>
<relativePath/><!-- lookup parent from repository -->
</parent>
<groupId>com.sunl</groupId>
<artifactId>boot-order-service-consumer</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>boot-order-service-consumer</name>
<description>boot-order-service-consumer</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--导入接口层-->
<dependency>
<groupId>com.sunl</groupId>
<artifactId>boot-interface-api</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<!--hystrix集成依赖-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
<version>2.0.3.RELEASE</version>
</dependency>
<!--Dubbo集成SpringBoot起步依赖-->
<dependency>
<groupId>com.alibaba.spring.boot</groupId>
<artifactId>dubbo-spring-boot-starter</artifactId>
<version>2.0.0</version>
</dependency>
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>3.8.0</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.101tec</groupId>
<artifactId>zkclient</artifactId>
<version>0.11</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<testFailureIgnore>true</testFailureIgnore>
</configuration>
</plugin>
</plugins>
</build>
</project>
4.2 新建控制层调用业务接口
/**
* @program: boot-dubbo-demo
* @description: 订单控制层
* @author: Sunl
* @create: 2022-05-10 10:04
**/
@Controller
public class OrderController {
@Autowired
OrderService orderService;
/**
*
* @return
*/
@RequestMapping("/initOrder")
@ResponseBody
public String initOrder(){
return orderService.initOrder();
}
}
4.3 新增订单业务接口实现类
/**
* @program: dubbo
* @description: 订单服务业务层实现类
* @author: Sunl
* @create: 2022-05-01 12:39
**/
@Service
public class OrderServiceImpl implements OrderService {
@Reference(loadbalance = "random")
private UserService userService;
/**
* 调用服务异常执行方法
* */
public String fallbackMethod() {
System.out.println("========fallbackMethod===========");
return "熔断测试";
}
/**
* 初始化订单
* @HystrixCommand 注解是方法级别的,在你需要捕获的方法上加上注解
* fallbackMethod:标记的是捕获异常时需要执行的方法,方法名称跟value值要一样
* @return
*/
@HystrixCommand(fallbackMethod = "fallbackMethod")
@Override
public String initOrder() {
System.out.println("===========initOrder============");
return userService.getUserAddressList();
}
}
@Reference(loadbalance = “random”)是dubbo的注解,也是注入,他一般注入的是分布式的远程服务的对象,需要dubbo配置使用
配置dubbo属性
# 默认端口
server.port=8083
# 指定一个唯一的名称
dubbo.application.name=boot-order-service-consumer
# 注册中心
dubbo.registry.address=zookeeper://localhost:2181
dubbo.registry.protocol=zookeeper
4.4 配置启动类,并启动
@EnableDubbo
@EnableHystrix
@SpringBootApplication
public class BootOrderServiceConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(BootOrderServiceConsumerApplication.class, args);
}
}
打开http://localhost:7001/确认消费者服务打开
调用http://localhost:8083/initOrder接口