中dubbo所需要的依賴_Dubbo整合Springboot框架
阿新 • • 發佈:2021-02-08
技術標籤:中dubbo所需要的依賴
本文使用的是alibaba的Dubbo。
Dubbo整合Springboot可以分為四步:
第一步:首先需要了解Dubbo官方給的建議,至少有三個工程:
介面工程:主要存實體bean和業務介面
服務提供者:業務介面的實現類和呼叫資料持久層,並將服務註冊到註冊中心
服務消費者:處理瀏覽器客戶端傳送的請求和從註冊中心呼叫服務提供者提供的服務
上面的聽起來很拗口,我們來實現一個工程試試。
首先,建立上述的三個工程:
這裡要注意:interface建立Maven專案就好了。其他兩個是springboot專案。
第二步:新增POM依賴
<!--alibaba的Dubbo整合springboot依賴--> <dependency> <groupId>com.alibaba.spring.boot</groupId> <artifactId>dubbo-spring-boot-starter</artifactId> <version>2.0.0</version> </dependency> <dependency> <groupId>com.101tec</groupId> <artifactId>zkclient</artifactId> <version>0.10</version> </dependency> <dependency> <groupId>com.kunkun.springboot</groupId> <artifactId>05-springboot-dubbo-interface</artifactId> <version>1.0.0</version></dependency>
這邊主要有三個依賴:alibaba的dubbo整合springboot依賴和zookeeper依賴,以及我們的介面工程的依賴。
這裡的依賴在服務提供者和消費者的pom檔案中都需要新增。
第三步:新增配置
服務提供者的application.properties:
#springboot的應用名稱(不能少,可以變) spring.application.name=05-springboot-dubbo-provider #是否是dubbo服務端(服務提供者) spring.dubbo.server = true #dubbo的註冊中心,如果位N/A表示不使用註冊中心 #我們使用zookeeper spring.dubbo.registry = zookeeper://127.0.0.1:2181
服務消費者的配置:
#springboot的應用名稱(不能少,可以變)
spring.application.name=05-springboot-dubbo-consumer
#dubbo的註冊中心,如果位N/A表示不使用註冊中心
#我們使用zookeeper
spring.dubbo.registry = zookeeper://127.0.0.1:2181
第四步:寫程式碼
首先,是介面專案的程式碼:
@Data public class Student implements Serializable { private static final long serialVersionUID = -302975163235439602L; private Integer id; private String name; private Integer age; public Student(Integer id,String name,Integer age){ this.age = age; this.id = id; this.name = name; } }
import com.kunkun.springboot.model.Student;
public interface StudentService {
public Student getStudentById();
}
然後是服務提供者的程式碼:
//dubbo的service
@Component //表示我這個類是spring的一個bean
@Service(timeout = 100,retries = 1)//相當於原來用xml中<dubbo:service interface="xxx" , ref = "xxx">
public class StudentServiceImpl implements StudentService {
@Override
public Student getStudentById() {
return new Student(1,"zhangsan",10);
}
}
這邊需要注意的就是註解@Service需要使用的是dubbo的service,不可以使用spring的@Service。
最後是服務消費者的程式碼:就是完成請求過來的處理
@RestController
public class StudentController {
@Reference
private StudentService studentService;
@RequestMapping("/")
public Object student(){
return studentService.getStudentById();
}
}
這邊需要注意的就是@AutoWired要換成@Reference
最後,需要在Application上面加上@EnableDubboConfiguration
@SpringBootApplication
@EnableDubboConfiguration
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}