SpringCloud實踐準備
專案技術版本
SpringCloud版本:Dalston.SR1,SpringBoot版本:1.5.9
專案說明
專案是使用SpringCloud將四個工程進行整合,microservicecloud整體父工程Project,microservicecloud-api公共子模組Module,microservicecloud-provider-dept-8001部門微服務提供者Module,microservicecloud-consumer-dept-80部門微服務消費者Module。
1.父類專案建立
在邏輯檢視中選擇new-Maven Project-勾上建立簡單專案-選擇pom方式
pom.xml檔案
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.luo.springcloud</groupId>
<artifactId>microservicecloud</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>pom</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<junit.version>4.12</junit.version>
<log4j.version>1.2.17</log4j.version>
<lombok.version>1.16.18</lombok.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Dalston.SR1</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>1.5.9.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.0.4</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.31</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>1.2.3</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
</project>
複製程式碼
2.公共元件專案建立
在父專案上建立microservicecloud-api專案,注意是在microservicecloud上new一個maven module,packaging選擇jar
POM.xml檔案
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.luo.springcloud</groupId>
<artifactId>microservicecloud</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>microservicecloud-api</artifactId>
<dependencies><!-- 當前Module需要用到的jar包,按自己需求新增,如果父類已經包含了,可以不用寫版本號 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
</dependencies>
</project>
複製程式碼
Dept實體類
public class Dept implements Serializable{
private Long deptno; // 主鍵
private String dname; // 部門名稱、
private String db_source; // 來自那個資料庫,因為微服務可以一個服務對應一個資料庫,同一個資訊被儲存到不同的資料庫
public Dept() {
super();
}
public Dept(Long deptno, String dname, String db_source) {
super();
this.deptno = deptno;
this.dname = dname;
this.db_source = db_source;
}
public Long getDeptno() {
return deptno;
}
public void setDeptno(Long deptno) {
this.deptno = deptno;
}
public String getDname() {
return dname;
}
public void setDname(String dname) {
this.dname = dname;
}
public String getDb_source() {
return db_source;
}
public void setDb_source(String db_source) {
this.db_source = db_source;
}
@Override
public String toString() {
return "Dept [deptno=" + deptno + ", dname=" + dname + ", db_source=" + db_source + "]";
}
複製程式碼
當我們每次都需要建立一個實體類的getter,setter,toString和構造器等方法時,如果增加一個欄位就要重新生成方法,為了簡化這種重複的操作,我們在前面的pom中引入了lombok,同樣的實體類,使用方法如下
@SuppressWarnings("serial")
@AllArgsConstructor
@NoArgsConstructor
@Data
@Accessors(chain=true)
public class Dept implements Serializable{
private Long deptno; // 主鍵
private String dname; // 部門名稱
// 來自那個資料庫,因為微服務可以一個服務對應一個資料庫,同一個資訊被儲存到不同的資料庫
private String db_source;
}
複製程式碼
lombok安裝方法
拷貝lombok-1.16.18.jar到Eclipse目錄下,執行java -jar D:\javasoft\eclipse-jee-neon-3-win32-x86_64\eclipse\ombok-1.16.18.jar,然後,彈框中選擇Eclipse安裝目錄,選擇install即可。
lombok註解使用
@Data :註解在類上;提供類所有屬性的 getting 和 setting 方法,此外還提供了equals、canEqual
@Setter:註解在屬性上;為屬性提供 setting 方法
@Getter:註解在屬性上;為屬性提供 getting 方法
@Log4j :註解在類上;為類提供一個 屬性名為log 的 log4j 日誌物件
@NoArgsConstructor:註解在類上;為類提供一個無參的構造方法
@AllArgsConstructor:註解在類上;為類提供一個全參的構造方法
@Accessors(chain=true):可以使用鏈式寫法
複製程式碼
lombok測試
@SuppressWarnings("serial")
@AllArgsConstructor
@NoArgsConstructor
@Data
@Accessors(chain=true)
public class Dept implements Serializable{
private Long deptno; // 主鍵
private String dname; // 部門名稱、
private String db_source; // 來自那個資料庫,因為微服務可以一個服務對應一個資料庫,同一個資訊被儲存到不同的資料庫
public static void main(String[] args) {
Dept dept = new Dept();
dept.setDeptno(12L).setDname("開發部").setDb_source("DB01");
}
}
複製程式碼
注意內容
實體類必須實現Serializable介面
打包使用
公共元件模組寫好後可以點選run as 選擇maven clean ,然後在選擇maven install。其他模組引用的方法如下
<groupId>com.atguigu.springcloud</groupId>
<artifactId>microservicecloud-api</artifactId>
<version>0.0.1-SNAPSHOT</version>
複製程式碼
3.部門微服務提供者
首先現在父類專案上new一個maven module,microservicecloud-provider-dept-8001修改pom.xml檔案
pom.xml檔案
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.luo.springcloud</groupId>
<artifactId>microservicecloud</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>microservicecloud-provider-dept-8001</artifactId>
<dependencies>
<!-- 引入自己定義的api通用包,可以使用Dept部門Entity -->
<dependency>
<groupId>com.luo.springcloud</groupId>
<artifactId>microservicecloud-api</artifactId>
<version>${project.version}</version>
</dependency>
<!-- actuator監控資訊完善 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!-- 將微服務provider側註冊進eureka -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jetty</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<!-- 修改後立即生效,熱部署 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>springloaded</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
</dependencies>
</project>
複製程式碼
application.yml檔案
server:
port: 8001
mybatis:
config-location: classpath:mybatis/mybatis.cfg.xml # mybatis配置檔案所在路徑
type-aliases-package: com.luo.springcloud.entities # 所有Entity別名類所在包
mapper-locations:
- classpath:mybatis/mapper/**/*.xml # mapper對映檔案
spring:
application:
name: microservicecloud-dept
datasource:
type: com.alibaba.druid.pool.DruidDataSource # 當前資料來源操作型別
driver-class-name: org.gjt.mm.mysql.Driver # mysql驅動包
url: jdbc:mysql://localhost:3306/cloudDB01 # 資料庫名稱
username: root
password: 1234
dbcp2:
min-idle: 5 # 資料庫連線池的最小維持連線數
initial-size: 5 # 初始化連線數
max-total: 5 # 最大連線數
max-wait-millis: 200 # 等待連線獲取的最大超時時間
eureka:
client: #客戶端註冊進eureka服務列表內
service-url:
defaultZone: http://localhost:7001/eureka
複製程式碼
mybatis下mybatis.cfg.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<setting name="cacheEnabled" value="true" /><!-- 二級快取開啟 -->
</settings>
</configuration>
複製程式碼
SQL語句
DROP DATABASE IF EXISTS cloudDB01 ;
CREATE DATABASE cloudDB01 CHARACTER SET UTF8 ;
USE cloudDB01 ;
CREATE TABLE dept (
deptno BIGINT NOT NULL PRIMARY KEY AUTO_INCREMENT,
dname VARCHAR (60),
db_source VARCHAR (60)
) ;
INSERT INTO dept(dname,db_source) VALUES('開發部',DATABASE());
INSERT INTO dept(dname,db_source) VALUES('人事部',DATABASE());
INSERT INTO dept(dname,db_source) VALUES('財務部',DATABASE());
INSERT INTO dept(dname,db_source) VALUES('市場部',DATABASE());
INSERT INTO dept(dname,db_source) VALUES('運維部',DATABASE());
複製程式碼
dao介面
@Mapper
public interface DeptDao {
public boolean addDept(Dept dept);
public Dept findById(Long id);
public List<Dept> findAll();
}
複製程式碼
DeptMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.luo.springcloud.dao.DeptDao">
<select id="findById" resultType="Dept" parameterType="Long">
select deptno,dname,db_source from dept where deptno=#{deptno};
</select>
<select id="findAll" resultType="Dept">
select deptno,dname,db_source from dept;
</select>
<insert id="addDept" parameterType="Dept">
INSERT INTO dept(dname,db_source) VALUES(#{dname},DATABASE());
</insert>
</mapper>
複製程式碼
DeptService
public interface DeptService {
public boolean add(Dept dept);
public Dept get(Long id);
public List<Dept> list();
}
複製程式碼
DeptServiceImpl
@Service
public class DeptServiceImpl implements DeptService{
@Autowired
private DeptDao dao;
@Override
public boolean add(Dept dept) {
return dao.addDept(dept);
}
@Override
public Dept get(Long id) {
return dao.findById(id);
}
@Override
public List<Dept> list() {
return dao.findAll();
}
}
複製程式碼
DeptController
@RestController
public class DeptController {
@Autowired
private DeptService service;
@RequestMapping(value="/dept/add",method=RequestMethod.POST)
public boolean add(@RequestBody Dept dept){
return service.add(dept);
}
@RequestMapping(value="dept/get/{id}",method=RequestMethod.GET)
public Dept get(@PathVariable("id") Long id){
return service.get(id);
}
@RequestMapping(value="dept/list",method=RequestMethod.GET)
public List<Dept> list(){
return service.list();
}
}
複製程式碼
建立主啟動類DeptProvider8001_App
@SpringBootApplication
public class DeptProvider8001_App {
public static void main(String[] args) {
SpringApplication.run(DeptProvider8001_App.class, args);
}
}
複製程式碼
測試結果
輸入http://localhost:8001/dept/list以JSON的方式返回資料
4.部門微服務消費者
首先現在父類專案上new一個maven module,microservicecloud-consumer-dept-80修改pom.xml檔案
POM.xml檔案
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.luo.springcloud</groupId>
<artifactId>microservicecloud</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>microservicecloud-consumer-dept-80</artifactId>
<description>部門微服務消費者</description>
<dependencies>
<dependency><!-- 自己定義的api -->
<groupId>com.luo.springcloud</groupId>
<artifactId>microservicecloud-api</artifactId>
<version>${project.version}</version>
</dependency>
<!-- Ribbon相關 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-ribbon</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 修改後立即生效,熱部署 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>springloaded</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
</dependencies>
</project>
複製程式碼
application.yml檔案
server:
port: 80
複製程式碼
ConfigBean註解類
@Configuration
public class ConfigBean {
@Bean
public RestTemplate geRestTemplate(){
return new RestTemplate();
}
}
複製程式碼
RestTemplate
RestTemplate提供了多種便捷訪問遠端Http服務的方法,是一種簡單高效便捷的訪問restful服務模板類,是Spring提供的用於訪問Rest服務的客戶端模板工具類集,使用方法如下
(url,requestMap,ResponseBean.class)三個引數分別代表Rest請求地址,請求引數,HTTP響應轉換被轉換的物件型別
DeptController_Consumer
@RestController
public class DeptController_Consumer {
private static final String REST_URL_PREFIX = "http://localhost:8001";
@Autowired
private RestTemplate restTemplate;
@RequestMapping(value="/consumer/dept/add")
public boolean add(Dept dept){
return restTemplate.postForObject(REST_URL_PREFIX+"/dept/add", dept, Boolean.class);
}
@RequestMapping(value="/consumer/dept/get/{id}")
public Dept get(@PathVariable("id") Long id){
return restTemplate.getForObject(REST_URL_PREFIX+"/dept/get/"+id, Dept.class);
}
@RequestMapping(value="/consumer/dept/list")
public Dept list(){
return restTemplate.getForObject(REST_URL_PREFIX+"/dept/list/", Dept.class);
}
}
複製程式碼
DeptConsumer80_App主類
@SpringBootApplication
public class DeptConsumer80_App {
public static void main(String[] args) {
SpringApplication.run(DeptConsumer80_App.class, args);
}
}
複製程式碼
測試結果
http://localhost/consumer/dept/list
http://localhost/consumer/dept/get/2
http://localhost/consumer/dept/add?dname=AI