Dubbo Spring Cloud 服务提供方(非Web应用)开发步骤

注册中心采用阿里巴巴Nacos
服务容器为Netty,端口为9090
dubbo协议在20880+n端口暴露服务

接口

接口定义

public interface UserService {

    boolean save(User user);

    boolean remove(Long userId);

    Collection<User> findAll();
}
public interface RestService {

    String param(String param);

    String params(int a, String b);

    String headers(String header, String header2, Integer param);

    String pathVariables(String path1, String path2, String param);

    String form(String form);

    User requestBodyMap(Map<String, Object> data, String param);

    Map<String, Object> requestBodyUser(User user);
}

工具类

import org.apache.dubbo.rpc.RpcContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Logger Utilities.
 */
public abstract class LoggerUtils {

    private static final Logger logger = LoggerFactory.getLogger(LoggerUtils.class);

    public static void log(String url, Object result) {
        String message = String
                .format("The client[%s] uses '%s' protocol to call %s : %s",
                        RpcContext.getContext().getRemoteHostName(),
                        RpcContext.getContext().getUrl() == null ? "N/A"
                                : RpcContext.getContext().getUrl().getProtocol(),
                        url, result);
        if (logger.isInfoEnabled()) {
            logger.info(message);
        }
    }

}

依赖引入

<dependencies>

    <!-- Resolve the Dubbo REST RPC issue -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.1.0</version>
    </dependency>

    <!-- Resolve the Spring Cloud registration issue -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
    </dependency>

    <!-- Sample API -->
    <dependency>
        <groupId>com.alibaba.cloud</groupId>
        <artifactId>spring-cloud-dubbo-sample-api</artifactId>
        <version>${project.version}</version>
    </dependency>

    <!-- Dubbo Spring Cloud Starter -->
    <dependency>
        <groupId>com.alibaba.cloud</groupId>
        <artifactId>spring-cloud-starter-dubbo</artifactId>
    </dependency>

    <!-- Spring Cloud Nacos Service Discovery -->
    <dependency>
        <groupId>com.alibaba.cloud</groupId>
        <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
    </dependency>

    <!-- REST support dependencies -->
    <dependency>
        <groupId>io.netty</groupId>
        <artifactId>netty-all</artifactId>
    </dependency>

    <dependency>
        <groupId>org.jboss.resteasy</groupId>
        <artifactId>resteasy-jaxrs</artifactId>
    </dependency>

    <dependency>
        <groupId>org.jboss.resteasy</groupId>
        <artifactId>resteasy-client</artifactId>
    </dependency>

    <dependency>
        <groupId>org.jboss.resteasy</groupId>
        <artifactId>resteasy-netty4</artifactId>
    </dependency>

    <dependency>
        <groupId>javax.validation</groupId>
        <artifactId>validation-api</artifactId>
    </dependency>

    <dependency>
        <groupId>org.jboss.resteasy</groupId>
        <artifactId>resteasy-jackson-provider</artifactId>
    </dependency>

    <dependency>
        <groupId>org.jboss.resteasy</groupId>
        <artifactId>resteasy-jaxb-provider</artifactId>
    </dependency>

    <dependency>
        <groupId>org.hibernate.validator</groupId>
        <artifactId>hibernate-validator</artifactId>
    </dependency>

</dependencies>

项目配置

  • bootstrap.yaml
spring:
  application:
    name: spring-cloud-alibaba-dubbo-provider
  main:
    allow-bean-definition-overriding: true
  profiles: nacos
  cloud:
    nacos:
      username: test
      password: test
      discovery:
        enabled: true
        register-enabled: true
        server-addr: 192.168.1.5:8848
        context-path: /nacos
        ephemeral: false
  • application.yaml
dubbo:
  scan:
    base-packages: com.alibaba.cloud.dubbo.service
  protocols:
    dubbo:
      name: dubbo
      port: -1
    rest:
      name: rest
      port: 9090
      server: netty
feign:
  hystrix:
    enabled: true

服务实现

@EnableDiscoveryClient
@EnableAutoConfiguration
public class DubboSpringCloudProviderBootstrap {

    public static void main(String[] args) {
        new SpringApplicationBuilder(DubboSpringCloudProviderBootstrap.class)
                .properties("spring.profiles.active=nacos").web(WebApplicationType.NONE)
                .run(args);
    }

}
import org.apache.dubbo.config.annotation.DubboService;

/**
 * In-Memory {@link UserService} implementation.
 */
@DubboService(protocol = "dubbo")
public class InMemoryUserService implements UserService {

    private Map<Long, User> usersRepository = new HashMap<>();

    @Override
    public boolean save(User user) {
        return usersRepository.put(user.getId(), user) == null;
    }

    @Override
    public boolean remove(Long userId) {
        return usersRepository.remove(userId) != null;
    }

    @Override
    public Collection<User> findAll() {
        return usersRepository.values();
    }
}
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;

import org.apache.dubbo.config.annotation.DubboService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static com.alibaba.cloud.dubbo.util.LoggerUtils.log;
import static org.springframework.util.MimeTypeUtils.APPLICATION_JSON_VALUE;

/**
 * Default {@link RestService}.
 */
@DubboService(version = "1.0.0", protocol = { "dubbo", "rest" })
@Path("/")
public class StandardRestService implements RestService {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    @Path("param")
    @GET
    public String param(@QueryParam("param") String param) {
        log("/param", param);
        return param;
    }

    @Override
    @Path("params")
    @POST
    public String params(@QueryParam("a") int a, @QueryParam("b") String b) {
        log("/params", a + b);
        return a + b;
    }

    @Override
    @Path("headers")
    @GET
    public String headers(@HeaderParam("h") String header,
            @HeaderParam("h2") String header2, @QueryParam("v") Integer param) {
        String result = header + " , " + header2 + " , " + param;
        log("/headers", result);
        return result;
    }

    @Override
    @Path("path-variables/{p1}/{p2}")
    @GET
    public String pathVariables(@PathParam("p1") String path1,
            @PathParam("p2") String path2, @QueryParam("v") String param) {
        String result = path1 + " , " + path2 + " , " + param;
        log("/path-variables", result);
        return result;
    }

    // @CookieParam does not support : https://github.com/OpenFeign/feign/issues/913
    // @CookieValue also does not support

    @Override
    @Path("form")
    @POST
    public String form(@FormParam("f") String form) {
        return String.valueOf(form);
    }

    @Override
    @Path("request/body/map")
    @POST
    @Produces(APPLICATION_JSON_VALUE)
    public User requestBodyMap(Map<String, Object> data,
            @QueryParam("param") String param) {
        User user = new User();
        user.setId(((Integer) data.get("id")).longValue());
        user.setName((String) data.get("name"));
        user.setAge((Integer) data.get("age"));
        log("/request/body/map", param);
        return user;
    }

    @Path("request/body/user")
    @POST
    @Override
    @Consumes(MediaType.APPLICATION_JSON)
    public Map<String, Object> requestBodyUser(User user) {
        Map<String, Object> map = new HashMap<>();
        map.put("id", user.getId());
        map.put("name", user.getName());
        map.put("age", user.getAge());
        return map;
    }
}

版权声明:
作者:Joe.Ye
链接:https://www.appblog.cn/index.php/2023/04/01/dubbo-spring-cloud-service-provider-non-web-application-development-steps/
来源:APP全栈技术分享
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
打赏
海报
Dubbo Spring Cloud 服务提供方(非Web应用)开发步骤
注册中心采用阿里巴巴Nacos 服务容器为Netty,端口为9090 dubbo协议在20880+n端口暴露服务 接口 接口定义 public interface UserService { boolean sa……
<<上一篇
下一篇>>
文章目录
关闭
目 录