<dependency>
<groupId>org.apache.dubbogroupId>
<artifactId>dubboartifactId>
<version>2.7.5version>
dependency>
<dependency>
<groupId>org.apache.dubbogroupId>
<artifactId>dubbo-dependencies-zookeeperartifactId>
<version>2.7.5version>
<type>pomtype>
dependency>
注意:在使用的过程中,dubbo与zookeeper的依赖需要与springboot版本号一样
public interface TestService {
public String test01();
}
package com.lmx.service;
import org.apache.dubbo.config.annotation.Service;
@Service
public class TestServiceImpl implements TestService {
@Override
public String test01() {
return "priverder";
// return null;
}
}
注意:在案例中的@service注解是dubbo的注解,不是springboot自身的service注解
package com.lmx.web;
import com.lmx.service.TestService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestCotroller {
@Reference
private TestService testService;
@GetMapping("/savehello")
public String sayhello() {
return testService.test01();
}
}
通过@Refrence注解远程注入service层对象,@Refrence注解同样也是dubbo定义的注解
package com.lmx.service;
public interface TestService {
String test01();
}
正确的做法是,将共有的接口抽象到新的maven项目中,供两个消费者服务与提供者服务相同
dubbo:
application:
name: dubbo-springboot-demo-constomer
protocol:
name: dubbo
port: -1
registry:
id: zk-registry
timeout: 10000
address: zookeeper://192.168.253.128:2181
config-center:
timeout: 10000
address: zookeeper://192.168.253.128:2181
metadata-report:
timeout: 10000
address: zookeeper://192.168.253.128:2181
public class User implements Serializable {
private int id;
private String name;
private int age;
@Service(timeout = 3000, retries = 0)//连接时间为3秒,连接失败后,不进行重试
public class TestServiceImpl implements TestService {
@Override
public String test01() {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "priverder";
// return null;
}
}
@Reference(timeout = 1000,retries = 2)
private TestService testService;
@GetMapping("/savehello")
public String sayhello() {
new Thread(new Runnable() {
@SneakyThrows
@Override
public void run() {
int i=0;
while (true){
Thread.sleep(1000);
System.out.println(i+++"秒");
}
}
}).start();
return testService.test01();
}
注意:在开发过程中,需要将超时设置配置在提供者服务
@Reference(version = "2.0")
@Service(timeout = 3000, retries = 0,version = "1.0")//连接时间为3秒,连接失败后,不进行重试
@Service(timeout = 3000, retries = 0,version = "2.0")//连接时间为3秒,连接失败后,不进行重试
@Reference(version = "2.0",loadbalance = "random")
注:双击shift键可以弹出类搜索界面,点击ctrl+h键可以查看当前文件类的继承关系
@Reference(version ="${refrence.version}",loadbalance = "${refrence.loadbalance}",
cluster = "failover",mock = "com.lmx.service.TestMock")