Dubbo的mock自己折腾的实例,配置信息有点简陋,有点粗鄙,如果是处女座的程序员,就建议看看就行哈。
其实Dubbo的mock的实例原理简单而言就是调用真实的接口实现类不通,就会调用你的mock类(mock类和真实实现类都Implements 同一个接口,自己mock的名字要是:接口类名+mock)。
我这个人直接来例子,不太喜欢讲太多文绉绉的字。处女座的程序员就是这样的哈,比较直接。
接口定义和mock定义(可单独在一个maven module)
接口类:
package cn.nest.facde;
public interface HelloService {
String sayHello(String content);
}
mock类(mock类和接口类要在同一个项目中,其他项目方便maven依赖):
package cn.nest.facde;
@SuppressWarnings("unused")
public class HelloServiceMock implements HelloService {
public HelloServiceMock(){}
@Override
public String sayHello(String content) {
System.out.println("dubbo mock sample....");
return "say hello fail";
}
}
Dubbo的服务端
Spring 配置文件内容:
![](https://img.haomeiwen.com/i4034029/b8c1cea41aa31253.png)
接口实现类:
public class HelloServiceImpl implements HelloService {
@Override
public String sayHello(String s) {
System.out.println("dubbo customer param value: " + s);
//mock verify
try {
Thread.sleep(10 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
boolean isCustomer = RpcContext.getContext().isProviderSide();
System.out.println("provider iscustomer :" + isCustomer);
return "say hello :" + s;
}
}
Dubbo消费端
消费端的配置:
spring 的配置最核心的配置:
<dubbo.reference id="helloService" interface="cn.nest.facde.HelloService" mock="true" timeout="1000" check="false">
消费端代码:
package cn.nest;
import cn.nest.facde.HelloService;
import cn.nest.facde.HelloSomeOneService;
import com.alibaba.dubbo.rpc.RpcContext;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.io.IOException;
@SpringBootApplication
public class DubboConsumerApplication implements CommandLineRunner {
ApplicationContext factory = new ClassPathXmlApplicationContext("classpath:spring-dubbo-consumer.xml");
public static void main(String[] args) {
new SpringApplicationBuilder().sources(DubboConsumerApplication.class).web(false).run(args);
while (true) {
try {
System.in.read();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void run(String... strings) throws Exception {
HelloService iHelloService = (HelloService) factory.getBean("helloService");
System.out.println(iHelloService.sayHello("botter"));
}
}
好了,基本上就这么多,第一次写技术博客,比较简陋,看不懂的请见谅,理解~~~~
网友评论