dubbo注解方式(直連,開發用)實現:
1.服務提供方
@Service
@Component
public class TestServiceIm implements TestService {
@Autowired
TestDao testDao;
public Date getNow() {
return testDao.getNow();
}
}
配置文件:dubbo注解掃描,放在spring注解掃描的前后都可以
<!-- 開啟注解掃描 -->
<context:component-scan base-package="cn.exam.service" />
<!--注解方式,掃描dubbo注解-->
<dubbo:annotation package="cn.exam.service"/>
<!-- 配置dubbo的服務提供 -->
<!-- 設置服務提供者的名字 (名字唯一.) -->
<dubbo:application name="exam-provider"/>
<!-- 以直連的方式提供服務.(方式2) -->
<dubbo:registry address="N/A"/>
<!-- 指定dubbo使用的端口號 -->
<dubbo:protocol name="dubbo" port="20880"/>
2.服務消費者
@RestController
public class TestController {
//必須指定url為dubbo協議本地地址及端口號
@Reference(url = "dubbo://127.0.0.1:20880")
TestService testService;
@RequestMapping("/test")
public String now(){
Date date=testService.getNow();
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String time = sdf.format(date);
return time;
}
}
配置文件:(先讓dubbo注解掃描,要不spring先注入過了,會出現NullPointerException)
<dubbo:annotation package="cn.exam.web"/>
<!-- 1.開啟web層注解掃描 -->
<context:component-scan base-package="cn.exam.web" />