SpringBoot整合Dubbo的第二种方式——API(自定义Configuration配置类)

Posted 张起灵-小哥

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringBoot整合Dubbo的第二种方式——API(自定义Configuration配置类)相关的知识,希望对你有一定的参考价值。

1.文档参照

dubbo配置官方文档


2.三个工程

2.1 公共接口工程

参考这篇文章:SpringBoot整合Dubbo的第一种方式

2.2 服务提供者

首先我们注释掉配置文件中的相关内容,只留下应用名(不留也可以)。

spring.application.name=boot-user-service-provider
#dubbo.application.name=boot-user-service-provider
#
#dubbo.scan.base-packages=com.szh.service.impl
#
#dubbo.registry.address=127.0.0.1:2181
#dubbo.registry.protocol=zookeeper
#
#dubbo.protocol.name=dubbo
#dubbo.protocol.port=20880
#
#dubbo.monitor.protocol=registry
package com.szh.service.impl;

import com.szh.gmall.bean.UserAddress;
import com.szh.gmall.service.UserService;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 1.将服务提供者注册到注册中心
 *      1) 引入dubbo依赖、zookeeper客户端依赖
 *      2) 配置服务提供者
 * 2.让服务消费者从注册中心订阅服务提供者的相关服务
 */
@Service
@DubboService(interfaceClass = UserService.class, version = "1.0.0")
public class UserServiceImpl implements UserService 

    //The default value of $dubbo.application.name is $spring.application.name
    @Value("$spring.application.name")
    private String applicationName;

    @Override
    public List<UserAddress> getUserAddressList(String userId) 
        UserAddress userAddress1 = new UserAddress(1, "浙江省杭州市", "1", "张三", "123456", "Y");
        UserAddress userAddress2 = new UserAddress(2, "湖北省武汉市", "1", "李四", "999999", "N");
        try 
            TimeUnit.MILLISECONDS.sleep(2000); //测试timeout
//            TimeUnit.MILLISECONDS.sleep(4000); //测试重试次数
         catch (InterruptedException e) 
            e.printStackTrace();
        
        System.out.println(applicationName + " old....");
        return Arrays.asList(userAddress1, userAddress2);
    

这里其实还有UserService的第二个实现类,我这里就不给出代码了,可以参考上面链接的那篇文章。

下面我们主要给出第二种实现方式的核心:自定义Config配置类。

package com.szh.config;

import com.szh.gmall.service.UserService;
import org.apache.dubbo.config.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;

/**
 *
 */
@Configuration
public class MyDubboConfig 

    @Bean
    public ApplicationConfig applicationConfig() 
        ApplicationConfig applicationConfig = new ApplicationConfig();
        applicationConfig.setName("boot-user-service-provider");
        return applicationConfig;
    

    @Bean
    public RegistryConfig registryConfig() 
        RegistryConfig registryConfig = new RegistryConfig();
        registryConfig.setProtocol("zookeeper");
        registryConfig.setAddress("127.0.0.1:2181");
        return registryConfig;
    

    @Bean
    public ProtocolConfig protocolConfig() 
        ProtocolConfig protocolConfig = new ProtocolConfig();
        protocolConfig.setName("dubbo");
        protocolConfig.setPort(20880);
        return protocolConfig;
    

    //下面的配置可以替代 @DubboService 注解(也即注释掉这个注解,也可正常运行)
    @Bean
    public ServiceConfig<UserService> serviceConfig(@Qualifier("userServiceImpl") UserService userService) 
        ServiceConfig<UserService> serviceConfig = new ServiceConfig<>();
        serviceConfig.setInterface(UserService.class);
        serviceConfig.setRef(userService);

        MethodConfig methodConfig = new MethodConfig();
        methodConfig.setName("getUserAddressList");
        methodConfig.setTimeout(1000);
        List<MethodConfig> methodConfigList = new ArrayList<>();
        methodConfigList.add(methodConfig);

        serviceConfig.setMethods(methodConfigList);
        return serviceConfig;
    

主启动类上要加上关于Dubbo的包扫描注解。 

package com.szh;

import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;
import org.apache.dubbo.config.spring.context.annotation.EnableDubboConfig;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ImportResource;

@SpringBootApplication
@EnableDubbo(scanBasePackages = "com.szh")
public class BootUserServiceProviderApplication 

    public static void main(String[] args) 
        SpringApplication.run(BootUserServiceProviderApplication.class, args);
    


2.3 服务消费者

首先我们注释掉配置文件中的相关内容,只留下应用名(不留也可以)、端口号最好留下,因为服务提供者启动之后会占用8080,这里将服务消费者声明在8081端口启动。

server.port=8081

spring.application.name=boot-order-service-consumer
#dubbo.application.name=boot-order-service-consumer
#
#dubbo.registry.address=zookeeper://127.0.0.1:2181
#dubbo.monitor.protocol=registry

下面我们还是通过controller的方式去访问调用服务提供者。 

package com.szh.controller;

import com.szh.gmall.bean.UserAddress;
import com.szh.gmall.service.OrderService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 *
 */
@RestController
public class OrderController 

    @Autowired
    private OrderService orderService;

    @GetMapping(value = "/initOrder/userId")
    public List<UserAddress> initOrder(@PathVariable("userId") String userId) 
        return orderService.initOrder2(userId);
    

package com.szh.service.impl;

import com.szh.gmall.bean.UserAddress;
import com.szh.gmall.service.OrderService;
import com.szh.gmall.service.UserService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.Method;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 *
 */
@Service
public class OrderServiceImpl implements OrderService 

    @DubboReference(interfaceClass = UserService.class, //服务接口名
                    version = "1.0.0", //服务版本,与服务提供者的版本一致
                    check = false,  //启动时检查提供者是否存在,true报错,false忽略
                    timeout = 3000, //服务方法调用超时时间(毫秒)
                    methods = @Method(name = "getUserAddressList"), //精确到服务接口的某个方法
                    retries = 3) //远程服务调用重试次数,不包括第一次调用,不需要重试请设为0
    private UserService userService;

    @Override
    public List<UserAddress> initOrder2(String userId) 
        System.out.println("用户id:" + userId);
        List<UserAddress> addressList = userService.getUserAddressList(userId);
        return addressList;
    

    @Override
    public void initOrder(String userId) 

    

下面是核心的自定义Config配置类。

package com.szh.config;

import com.szh.gmall.service.UserService;
import org.apache.dubbo.config.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;

/**
 *
 */
@Configuration
public class MyDubboConfig 

    @Bean
    public ApplicationConfig applicationConfig() 
        ApplicationConfig applicationConfig = new ApplicationConfig();
        applicationConfig.setName("boot-order-service-consumer");
        return applicationConfig;
    

    @Bean
    public RegistryConfig registryConfig() 
        RegistryConfig registryConfig = new RegistryConfig();
        registryConfig.setProtocol("zookeeper");
        registryConfig.setAddress("127.0.0.1:2181");
        return registryConfig;
    

    @Bean
    public MonitorConfig monitorConfig() 
        MonitorConfig monitorConfig = new MonitorConfig();
        monitorConfig.setProtocol("registry");
        return monitorConfig;
    

    //下面这段代码可以替代 @DubboReference 注解
    @Bean
    public ReferenceConfig<UserService> referenceConfig() 
        ReferenceConfig<UserService> referenceConfig = new ReferenceConfig<>();
        referenceConfig.setInterface(UserService.class);
        referenceConfig.setVersion("1.0.0");
        referenceConfig.setTimeout(3000);
        referenceConfig.setRetries(3);

        MethodConfig methodConfig = new MethodConfig();
        methodConfig.setName("getUserAddressList");
        List<MethodConfig> methodConfigList = new ArrayList<>();
        methodConfigList.add(methodConfig);

        referenceConfig.setMethods(methodConfigList);
        return referenceConfig;
    

package com.szh;

import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ImportResource;

@SpringBootApplication
@EnableDubbo(scanBasePackages = "com.szh")
public class BootOrderServiceConsumerApplication 

    public static void main(String[] args) 
        SpringApplication.run(BootOrderServiceConsumerApplication.class, args);
    



3.启动测试

启动服务提供者和消费者之前,要先将zookeeper开启,然后再将dubbo管控台打开。

我这里为了方便,就直接在windows下启动zookeeper了,dubbo管控台开不开无所谓。

参考 https://blog.csdn.net/weixin_43823808/article/details/124494499

以上是关于SpringBoot整合Dubbo的第二种方式——API(自定义Configuration配置类)的主要内容,如果未能解决你的问题,请参考以下文章

SpringBoot整合Dubbo的第三种方式——XML配置 + @ImportResource

SpringBoot整合Dubbo的第三种方式——XML配置 + @ImportResource

SpringBoot整合Dubbo的第三种方式——XML配置 + @ImportResource

SpringBoot整合Dubbo的第一种方式——application.properties + @DubboService + @DubboReference

SpringBoot整合Dubbo的第一种方式——application.properties + @DubboService + @DubboReference

SpringBoot基础集成插件