2.搭建服务消费者user-consumer

搭建服务消费者user-consumer

1.创建user-consumer模块,导入依赖

  <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>


        <!--dubbo的起步依赖-->
        <dependency>
            <groupId>org.apache.dubbo</groupId>
            <artifactId>dubbo-spring-boot-starter</artifactId>
            <version>2.7.8</version>
        </dependency>

        <dependency>
            <groupId>org.apache.dubbo</groupId>
            <artifactId>dubbo-registry-nacos</artifactId>
            <version>2.7.8</version>
        </dependency>

2.配置引导类

@SpringBootApplication
public class UserConsumerApplication {
    public static void main(String[] args) {
        SpringApplication.run(UserConsumerApplication.class, args);
    }
}

3.Controller

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @DubboReference(version = "v2.0.0")
    private UserService userService;

    /**
     * 路径: /user/id
     * @param id 用户id
     * @return 用户
     */
    @GetMapping("/{id}")
    public User queryById(@PathVariable("id") Long id) {
        return userService.selectById(id);
    }


    /**
     * 根据id查询用户名
     * @param id
     * @return
     */
    @GetMapping("/username/{id}")
    public  String queryUserName(@PathVariable("id") Long id){
        return userService.queryUserName(id);
    }
}

4.Service

package com.zhang.service;


import com.zhang.domain.User;

public interface UserService {
    //根据id查询用户
    User selectById(Long id);

    //根据id查询用户名
    String queryUserName(Long id);
}

5.配置文件

server:
  port: 8082
spring:
  application:
    name: userconsumer
logging:
  level:
    cn.itcast: debug
  pattern:
    dateformat: HH:mm:ss:SSS
dubbo:
  registry:
    address: nacos://127.0.0.1:8848

6. 代码优化

将接口抽取为独立模块,并且把接口有关的domain都放到这个模块中

(1)创建user-api模块引入依赖

(2)将UserService接口和User对象导入user-api模块下

(3)User对象实现序列化接口
Dubbo中传输对象在RPC框架中,往往通过TCP协议进行数据传输对象需要实现序列化接口Serializable

posted @ 2022-11-12 20:29  给我手牵你走  阅读(23)  评论(0编辑  收藏  举报