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

注册中心采用阿里巴巴Nacos
服务容器为Tomcat,端口为8080
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>

    <!-- Production Ready features -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-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>

</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

feign:
  hystrix:
    enabled: true

server:
  port: 8080

management:
  endpoints:
    web:
      exposure:
        include: dubborestmetadata

服务实现

@EnableDiscoveryClient
@EnableAutoConfiguration
public class DubboSpringCloudWebProviderBootstrap {

    public static void main(String[] args) {
        new SpringApplicationBuilder(DubboSpringCloudWebProviderBootstrap.class)
                .properties("spring.profiles.active=nacos").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 org.apache.dubbo.config.annotation.DubboService;

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

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import static com.alibaba.cloud.dubbo.util.LoggerUtils.log;

/**
 * Spring MVC {@link RestService}.
 */
@DubboService(version = "1.0.0")
@RestController
public class SpringRestService implements RestService {

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

    @Override
    @GetMapping("/param")
    public String param(@RequestParam String param) {
        log("/param", param);
        return param;
    }

    @Override
    @PostMapping("/params")
    public String params(@RequestParam int a, @RequestParam String b) {
        log("/params", a + b);
        return a + b;
    }

    @Override
    @GetMapping("/headers")
    public String headers(@RequestHeader("h") String header,
            @RequestHeader("h2") String header2, @RequestParam("v") Integer param) {
        String result = header + " , " + header2 + " , " + param;
        log("/headers", result);
        return result;
    }

    @Override
    @GetMapping("/path-variables/{p1}/{p2}")
    public String pathVariables(@PathVariable("p1") String path1,
            @PathVariable("p2") String path2, @RequestParam("v") String param) {
        String result = path1 + " , " + path2 + " , " + param;
        log("/path-variables", result);
        return result;
    }

    @Override
    @PostMapping("/form")
    public String form(@RequestParam("f") String form) {
        return String.valueOf(form);
    }

    @Override
    @PostMapping(value = "/request/body/map",
            produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public User requestBodyMap(@RequestBody Map<String, Object> data,
            @RequestParam("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;
    }

    @PostMapping(value = "/request/body/user",
            consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @Override
    public Map<String, Object> requestBodyUser(@RequestBody 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-web-application-development-steps/
来源:APP全栈技术分享
文章版权归作者所有,未经允许请勿转载。

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