Dubbo学习(四)SpringMVC整合

Spring配置文件

Dubbo学习(四)SpringMVC整合_第1张图片

提供者和消费者,分别为两个spring工程

提供者

    Spring Configuration


    

    
    

    
    

    
    
    

消费者

   Spring MVC Configuration
    
    

    
    
    

    
    
    

pom配置

#接口文件导入
        
            com.maple.dubbodemo
            dubbo-api
            1.0-SNAPSHOT
            system
            ${project.basedir}/src/main/webapp/WEB-INF/lib/dubbo-api-1.0-SNAPSHOT.jar
        

其余pom配置见Dubbo学习(三)HelloWorld

提供者服务实现-注解方式

使用@Service

import com.alibaba.dubbo.rpc.RpcContext;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by maple on 2017-10-26.
 */
@Service
@com.alibaba.dubbo.config.annotation.Service
public class HelloServiceImpl implements HelloService {
    public String sayHello(String content) {
        System.out.println("[" + new SimpleDateFormat("HH:mm:ss").format(new Date()) + "] Hello " + content + ", request from consumer: " + RpcContext.getContext().getRemoteAddress());
        return "Hello " + content + ", response form provider: " + RpcContext.getContext().getLocalAddress();
    }
}

消费者使用-注解方式

使用@Reference

@Controller
@RequestMapping(value = "${adminPath}/test/testData")
public class TestDataController extends BaseController {

    @Reference
    HelloService helloService;

    @RequestMapping(value = "testService")
    @ResponseBody
    public String testService( ) {
        String s = "helloService is null";
        if (null == helloService){
            return s;
        }
        try {
            s = helloService.sayHello("test");
        }catch (Exception e){
            e.printStackTrace();
        }
        System.out.println("=======" + s);
        return s;
    }
}

注意

注解无效,空指针

原因:spring 扫描的时候无法识别@Reference ,dubbo的扫描也无法识别Spring @Controller,如果先扫了controller,这时候把控制器都实例化好了,再扫dubbo的服务,就会出现空指针。因此,提供者先扫描spring框架,完成spring部分的扫描,然后将为dubbo框架提供服务;消费者部分相反,先扫描dubbo服务,后扫描spring部分

事务注解问题@Transactional

被事务代理的spring service 使用注解方式发布Dubbo服务

你可能感兴趣的:(Dubbo学习(四)SpringMVC整合)