公共API项目中包含服务提供者和消费者共同要使用的接口。简答说就是这些接口先定义在一个公共的项目中,再将这个项目打成一个jar 包,服务提供者和消费者项目就可以依赖这个jar 包。服务提供者会具体实现这些接口,而服务消费者则是调用这些接口,即可完成远程调用。
package com.hejjon;
import com.hejjon.vo.UserVO;
import java.util.List;
public interface TestService {
void add(String user);
List list();
UserVO getById(String id);
}
也可以将一些公共的 Bean组件写在这个项目里。
2. 服务提供者和消费者环境搭建pom.xml 文件中导入 Dubbo 的依赖
org.apache.dubbo
dubbo
${dubbo.version}
org.apache.dubbo
dubbo-dependencies-zookeeper
${dubbo.version}
pom
org.slf4j
slf4j-log4j12
org.apache.dubbo
dubbo-spring-boot-starter
${dubbo.version}
org.slf4j
slf4j-log4j12
还有 公共接口项目的依赖
com.hejjon
dubbo-service-interface
1.0.1
3. 服务提供者
TestServiceImpl.java
package com.hejjon.service;
import com.hejjon.TestService;
import com.hejjon.vo.UserVO;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
@DubboService(version = "1.0.0", interfaceClass = TestService.class)
public class TestServiceImpl implements TestService {
@Override
public void add(String s) {
System.out.println("TestServiceImpl.add 入参:" + s);
}
@Override
public List list() {
return null;
}
@Override
public UserVO getById(String s) {
System.out.println("s = " + s);
UserVO vo = new UserVO();
vo.setUserId("1");
vo.setUsername("张三" + s);
vo.setSex(0);
return vo;
}
}
使用 @DubboService 注解加在服务实现类上。
4. 服务消费者package com.hejjon.controller;
import com.hejjon.TestService;
import com.hejjon.vo.UserVO;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/consumer")
public class ConsumerTestController {
@DubboReference(version = "1.0.0")
private TestService testService;
@GetMapping("/test1")
public UserVO test1() {
UserVO userVO = testService.getById("123");
System.out.println(userVO);
return userVO;
}
}
使用@DubboReference 注解,注入服务接口即可实现远程服务的调用。
5. 注意点上面案例中有一个接口是返回自定义的实体类型,注意这个实体类 UserVO 必须要序列化,即实现 Serializable 接口。



