关于消费端接入dubbo,连接失败问题

服务端定义好的dubbo接口,确定已经在zookeeper上了,消费端需要连接对应的zookeeper.

首先引入maven

<dependency>
            <groupId>org.apache.dubbo</groupId>
            <artifactId>dubbo</artifactId>
            <version>2.7.8</version>
        </dependency>
        <dependency>
            <groupId>org.apache.zookeeper</groupId>
            <artifactId>zookeeper</artifactId>
            <version>3.4.13</version>
            <exclusions>
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>slf4j-log4j12</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.apache.curator</groupId>
            <artifactId>curator-framework</artifactId>
            <version>2.12.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.curator</groupId>
            <artifactId>curator-recipes</artifactId>
            <version>2.12.0</version>
        </dependency>

配置文件yml

dubbo:
  application:
    name: coupon-admin
  registry: 
    address: zookeeper://127.0.0.1:2181
    # 连接超时时间
    timeout: 20000
  protocol:
    name: dubbo
    port: 20801
  consumer:
    timeout: 60000

关键点在于dubbo.registry.timeout ,之前没有配置默认是5秒,一直报错连接不上zookeeper,后来加上了超时时间,才注册成功。

在需要使用的地方使用@DubboReference引入服务:

import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Author johnson
 * @Date 2023/6/1
 */
@Service
public class AppDubboService {

    @DubboReference
    private AppInfoDispatcher appInfoDispatcher;
public Map getApps(){
    
       return appDispatcher.getAppMap();
      
    }
}

在服务启动类上加上注解 @EnableDubbo

@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class, RabbitAutoConfiguration.class})
@EnableDubbo
public class AdminApplication
{
    public static void main(String[] args)
    {
        SpringApplication.run(AdminApplication.class, args);
        System.out.println("http://localhost:8088/");
    }
}

注意如果服务端连接正常,但是接口未注册上去一定要注意对应的@Service 注解是否引用了dubbo的,只有使用org.apache.dubbo.config.annotation.Service 或者@DubboService 才能生效

 

posted @ 2023-06-02 10:33  Johnson_wang  阅读(102)  评论(0编辑  收藏  举报