【基于Dubbo3.X版本】SpringBoot整合Dubbo

2022/4/30 6:13:03

本文主要是介绍【基于Dubbo3.X版本】SpringBoot整合Dubbo,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

【基于Dubbo3.X版本】SpringBoot与dubbo整合的三种方式:

1)导入dubbo-starter,在application.properties配置属性,使用@DubboService【暴露服务】使用@DubboReference【引用服务】,使用@EnableDubbo注解。

2)保留dubbo的xml配置文件,导入dubbo-starter,使用@ImportResource导入dubbo的配置文件即可。不再使用@DubboService【暴露服务】使用@DubboReference【引用服务】,不使用@EnableDubbo注解。

3)使用注解API的方式,将每一个组件手动创建到容器中,让dubbo来扫描其他的组件,使用@DubboService【暴露服务】使用@DubboReference【引用服务】,使用@EnableDubbo注解。

【1】第一种方式-无dubbo配置文件
使用注解和application.properties,无dubbo额外配置文件。

provider

server.port=8088
dubbo.application.name=user-service-provider
dubbo.registry.address=127.0.0.1:2181
dubbo.registry.protocol=zookeeper
dubbo.protocol.name=dubbo
dubbo.protocol.port=20881
dubbo.monitor.address=registry

@DubboService暴露服务

//可在注解内设置属性如下
@Target({ElementType.TYPE, ElementType.METHOD})
@Inherited
public @interface DubboService {
    /**
     * Interface class, default value is void.class
     */
    Class<?> interfaceClass() default void.class;
    /**
     * Interface class name, default value is empty string
     */
    String interfaceName() default "";
    /**
     * Service version, default value is empty string
     */
    String version() default "";
    /**
     * Service group, default value is empty string
     */
    String group() default "";
    /**
     * Service path, default value is empty string
     */
    String path() default "";
    /**
     * Whether to export service, default value is true
     */
    boolean export() default true;
    /**
     * Service token, default value is empty string
     */
    String token() default "";
    /**
     * Whether the service is deprecated, default value is false
     */
    boolean deprecated() default false;
    /**
     * Whether the service is dynamic, default value is true
     */
    boolean dynamic() default true;
    /**
     * Access log for the service, default value is empty string
     */
    String accesslog() default "";
    /**
     * Maximum concurrent executes for the service, default value is -1 - no limits
     */
    int executes() default -1;
    /**
     * Whether to register the service to register center, default value is true
     */
    boolean register() default true;
    /**
     * Service weight value, default value is -1
     */
    int weight() default -1;
    /**
     * Service doc, default value is empty string
     */
    String document() default "";
    /**
     * Delay time for service registration, default value is -1
     */
    int delay() default -1;
    /**
     * @see DubboService#stub()
     * @deprecated
     */
    String local() default "";
    /**
     * Service stub name, use interface name + Local if not set
     */
    String stub() default "";
    /**
     * Cluster strategy, legal values include: failover, failfast, failsafe, failback, forking
     * you can use {@link org.apache.dubbo.common.constants.ClusterRules#FAIL_FAST} ……
     */
    String cluster() default ClusterRules.EMPTY;
    /**
     * How the proxy is generated, legal values include: jdk, javassist
     */
    String proxy() default "";
    /**
     * Maximum connections service provider can accept, default value is -1 - connection is shared
     */
    int connections() default -1;
    /**
     * The callback instance limit peer connection
     * <p>
     * see org.apache.dubbo.common.constants.CommonConstants.DEFAULT_CALLBACK_INSTANCES
     */
    int callbacks() default -1;
    /**
     * Callback method name when connected, default value is empty string
     */
    String onconnect() default "";
    /**
     * Callback method name when disconnected, default value is empty string
     */
    String ondisconnect() default "";
    /**
     * Service owner, default value is empty string
     */
    String owner() default "";
    /**
     * Service layer, default value is empty string
     */
    String layer() default "";
    /**
     * Service invocation retry times
     *
     * @see org.apache.dubbo.common.constants.CommonConstants#DEFAULT_RETRIES
     */
    int retries() default -1;
    /**
     * Load balance strategy, legal values include: random, roundrobin, leastactive
     *
     * you can use {@link org.apache.dubbo.common.constants.LoadbalanceRules#RANDOM} ……
     */
    String loadbalance() default ClusterRules.EMPTY;
    /**
     * Whether to enable async invocation, default value is false
     */
    boolean async() default false;
    /**
     * Maximum active requests allowed, default value is -1
     */
    int actives() default -1;
    /**
     * Whether the async request has already been sent, the default value is false
     */
    boolean sent() default false;
    /**
     * Service mock name, use interface name + Mock if not set
     */
    String mock() default "";

    /**
     * Whether to use JSR303 validation, legal values are: true, false
     */
    String validation() default "";
    /**
     * Timeout value for service invocation, default value is -1
     */
    int timeout() default -1;
    /**
     * Specify cache implementation for service invocation, legal values include: lru, threadlocal, jcache
     */
    String cache() default "";
    /**
     * Filters for service invocation
     *
     * @see Filter
     */
    String[] filter() default {};
    /**
     * Listeners for service exporting and unexporting
     *
     * @see ExporterListener
     */
    String[] listener() default {};
    /**
     * Customized parameter key-value pair, for example: {key1, value1, key2, value2}
     */
    String[] parameters() default {};
    /**
     * Application spring bean name
     * @deprecated This attribute was deprecated, use bind application/module of spring ApplicationContext
     */
    @Deprecated
    String application() default "";
    /**
     * Module spring bean name
     */
    String module() default "";

    /**
     * Provider spring bean name
     */
    String provider() default "";
    /**
     * Protocol spring bean names
     */
    String[] protocol() default {};
    /**
     * Monitor spring bean name
     */
    String monitor() default "";
    /**
     * Registry spring bean name
     */
    String[] registry() default {};
    /**
     * Service tag name
     */
    String tag() default "";
    /**
     * methods support
     *
     * @return
     */
    Method[] methods() default {};
    /**
     * the scope for referring/exporting a service, if it's local, it means searching in current JVM only.
     * @see org.apache.dubbo.rpc.Constants#SCOPE_LOCAL
     * @see org.apache.dubbo.rpc.Constants#SCOPE_REMOTE
     */
    String scope() default "";
    /**
     * Weather the service is export asynchronously
     */
    boolean exportAsync() default false;
}

consumer

server.port=8089
dubbo.application.name=boot-order-service-consumer
dubbo.registry.address=zookeeper://127.0.0.1:2181
dubbo.monitor.protocol=registry

@DubboReferecen引用服务

//注解内可设置的属性如下
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.ANNOTATION_TYPE})
public @interface DubboReference {
    Class<?> interfaceClass() default void.class;
    String interfaceName() default "";
    String version() default "";
    String group() default "";
    String url() default "";
    String client() default "";
    /** @deprecated */
    @Deprecated
    boolean generic() default false;
    /** @deprecated */
    @Deprecated
    boolean injvm() default true;
    boolean check() default true;
    boolean init() default true;
    boolean lazy() default false;
    boolean stubevent() default false;
    String reconnect() default "";
    boolean sticky() default false;
    String proxy() default "";
    String stub() default "";
    String cluster() default "";
    int connections() default -1;
    int callbacks() default -1;
    String onconnect() default "";
    String ondisconnect() default "";
    String owner() default "";
    String layer() default "";
    int retries() default -1;
    String loadbalance() default "";
    boolean async() default false;
    int actives() default -1;
    boolean sent() default false;
    String mock() default "";
    String validation() default "";
    int timeout() default -1;
    String cache() default "";
    String[] filter() default {};
    String[] listener() default {};
    String[] parameters() default {};
    /** @deprecated */
    @Deprecated
    String application() default "";
    String module() default "";
    String consumer() default "";
    String monitor() default "";
    String[] registry() default {};
    String protocol() default "";
    String tag() default "";
    String merger() default "";
    Method[] methods() default {};
    String id() default "";
    /** @deprecated */
    @Deprecated
    String[] services() default {};
    String[] providedBy() default {};
    String scope() default "";
    boolean referAsync() default false;
}

但是此种方式有个弊端,无法在方法级别进行详细控制,如下所示:

<dubbo:service interface="com.atguigu.gmall.service.UserService" ref="userServiceImpl1" timeout="1000" version="1.0.0" 
     stub="com.atguigu.gmall.service.stub.UserServiceStub">
     <dubbo:method name="getUserAddressList" timeout="1000"></dubbo:method>
</dubbo:service>

对于dubbo:service标签,dubbo同样提供了com.alibaba.dubbo.config.annotation.Service;注解暴露服务,还可以在该注解上面详细配置属性。

但是没有提供dubbo:method标签的对应注解。

【2】第二种-引入dubbo配置文件
上述提到了使用@ImportResource注解导入Spring的配置文件将dubbo的xml配置文件引入进来,取消application.properties中的dubbo配置和相关注解。
如下所示,修改主类://@EnableDubbo//开启基于注解的dubbo功能

@ImportResource(value={"classpath:provider.xml"})
@SpringBootApplication
public class BootUserServiceProviderApplication {
 
    public static void main(String[] args) {
        SpringApplication.run(BootUserServiceProviderApplication.class, args);
    }
}

另外去掉UserServiceImpl上面的dubbo的service注解。

注释掉application.properties中的dubbo配置

同理,消费者也可以如此配置。

【3】第三种-使用注解API方式-推荐
这里需要参考官方文档API配置和注解配置将xml里面的东西编写为API代码再使用注解注册到容器中。

如下图所示,标明了标签和配置类对应关系:

img

provider 配置实例

@Configuration
public class MyDubboConfig {
    
    @Bean
    public ApplicationConfig applicationConfig() {
        ApplicationConfig applicationConfig = new ApplicationConfig();
        applicationConfig.setName("boot-user-service-provider");
        return applicationConfig;
    }
    
    //<dubbo:registry protocol="zookeeper" address="127.0.0.1:2181"></dubbo:registry>
    @Bean
    public RegistryConfig registryConfig() {
        RegistryConfig registryConfig = new RegistryConfig();
        registryConfig.setProtocol("zookeeper");
        registryConfig.setAddress("127.0.0.1:2181");
        return registryConfig;
    }
    
    //<dubbo:protocol name="dubbo" port="20882"></dubbo:protocol>
    @Bean
    public ProtocolConfig protocolConfig() {
        ProtocolConfig protocolConfig = new ProtocolConfig();
        protocolConfig.setName("dubbo");
        protocolConfig.setPort(20888);
        return protocolConfig;
    }
    
    /**
     *<dubbo:service interface="com.atguigu.gmall.service.UserService" 
        ref="userServiceImpl01" timeout="1000" version="1.0.0">
        <dubbo:method name="getUserAddressList" timeout="1000"></dubbo:method>
    </dubbo:service>
     */
    @Bean
    public ServiceConfig<UserService> userServiceConfig(UserService userService){
        ServiceConfig<UserService> serviceConfig = new ServiceConfig<>();
        serviceConfig.setInterface(UserService.class);
        serviceConfig.setRef(userService);
        serviceConfig.setVersion("1.0.0");
        
        //配置每一个method的信息
        MethodConfig methodConfig = new MethodConfig();
        methodConfig.setName("getUserAddressList");
        methodConfig.setTimeout(1000);
        
        //将method的设置关联到service配置中
        List<MethodConfig> methods = new ArrayList<>();
        methods.add(methodConfig);
        serviceConfig.setMethods(methods);
        return serviceConfig;
    }
 
//    <dubbo:provider timeout="1000"></dubbo:provider>
    @Bean
    public ProviderConfig providerConfig() {
        ProviderConfig providerConfig = new ProviderConfig();
        providerConfig.setTimeout(5000);
        return providerConfig;
    }
//    <dubbo:monitor address="127.0.0.1:7070"></dubbo:monitor>
    @Bean
    public MonitorConfig monitorConfig() {
        MonitorConfig monitorConfig = new MonitorConfig();
        monitorConfig.setAddress("127.0.0.1:7070");
        monitorConfig.setProtocol("registry");
        return monitorConfig;
    }

consumer配置实例

@Configuration
public class MyDubboConfig {
    
    @Bean
    public ApplicationConfig applicationConfig() {
        ApplicationConfig applicationConfig = new ApplicationConfig();
        applicationConfig.setName("boot-order-service-consumer");
        return applicationConfig;
    }
    
    //<dubbo:registry protocol="zookeeper" address="127.0.0.1:2181"></dubbo:registry>
    @Bean
    public RegistryConfig registryConfig() {
        RegistryConfig registryConfig = new RegistryConfig();
        registryConfig.setProtocol("zookeeper");
        registryConfig.setAddress("127.0.0.1:2181");
        return registryConfig;
    }
    
    
    /**
     *<dubbo:reference interface="com.web.gmall.service.UserService" 
        id="userService" timeout="5000" retries="3" version="*">
        <dubbo:method name="getUserAddressList" timeout="1000" retries="0"></dubbo:method>
    </dubbo:reference>
     */
    @Bean
    public ReferenceConfig<UserService> userReferenceConfig(){
        ReferenceConfig<UserService> serviceConfig = new ReferenceConfig<>();
        serviceConfig.setInterface(UserService.class);
        serviceConfig.setTimeout(5000);
        serviceConfig.setVersion("*");
        serviceConfig.setRetries(3);
        
        //配置每一个method的信息
        MethodConfig methodConfig = new MethodConfig();
        methodConfig.setName("getUserAddressList");
        methodConfig.setTimeout(1000);
        
        //将method的设置关联到service配置中
        List<MethodConfig> methods = new ArrayList<>();
        methods.add(methodConfig);
        serviceConfig.setMethods(methods);
        
        return serviceConfig;
    }
//    <dubbo:consumer check="false" timeout="5000"></dubbo:consumer>
    @Bean
    public ConsumerConfig consumerConfig() {
        ConsumerConfig consumerConfig = new ConsumerConfig();
        consumerConfig.setCheck(false);;
        consumerConfig.setTimeout(5000);
        return consumerConfig;
    }
//    <dubbo:monitor address="127.0.0.1:8888"></dubbo:monitor>
    @Bean
    public MonitorConfig monitorConfig() {
        MonitorConfig monitorConfig = new MonitorConfig();
        monitorConfig.setAddress("127.0.0.1:7070");
        monitorConfig.setProtocol("registry");
        return monitorConfig;
    }
}


这篇关于【基于Dubbo3.X版本】SpringBoot整合Dubbo的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程