springcloud微服務簡單例項(服務發現與註冊)
原理圖:
一.架構
1.建立一個SPRINGCLOUD專案
2.新增依賴:
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.17.RELEASE</version> </parent> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>Dalston.RELEASE</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement>
3.建立模組:
SPRINGCLOUD_EUREKASERVER (註冊中心)
SPRINGCLOUD_USERSERVICE (微服務)
SPRINGCLOUD_USERUI (客戶端)
二.模組程式碼
1.SPRINGCLOUD_EUREKASERVER模組
首先在pom.xml匯入依賴:
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka-server</artifactId>
</dependency>
</dependencies>
EurekaServer.java:
@SpringBootApplication //開啟Eureka Server @EnableEurekaServer public class EurekaServer { public static void main(String[] args) { new SpringApplicationBuilder(EurekaServer.class).web(true).run(args); } }
解釋:
@EnableEurekaServer註解:是啟用eureka的服務
@SpringBootApplication註解:
主要有3個註解:
[email protected]:這個主要有2個作用,元件掃描和自動裝配;
[email protected]:這個註解主要是繼承@Configuration註解,這個我們就是為了載入配置檔案用
[email protected]:自動生成spring的配置檔案
application.yml資原始檔:
#指定埠,預設是8761,不要改變
server:
port: 8761
eureka:
instance:
#將來註冊到註冊中心的微服務包括註冊中心都是用ip地址
prefer-ip-address: true
hostname: localhost
client:
#是否註冊到註冊中心 (註冊中心自己不需要註冊)
register-with-eureka: false
#是否抓取註冊中的註冊資訊
fetch-registry: false
#微服務和客戶端用來註冊和發現的地址
service-url:
defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
執行main方法,再進入瀏覽器查詢:http://localhost:8761/
2.SPRINGCLOUD_USERSERVICE模組
首先在pom.xml匯入依賴:
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.18</version>
<scope>provided</scope>
</dependency>
</dependencies>
UserService.java:
@SpringBootApplication
// 啟用eureka的客戶端
@EnableEurekaClient
public class UserService {
public static void main(String[] args) {
new SpringApplicationBuilder(UserService.class).web(true).run(args);
}
}
application.yml資原始檔:
server:
port: 8881
#給微服務設定一個名字
spring:
application:
name: userservice
#連線資料庫
datasource:
url: jdbc:mysql://localhost/mysql
username: root
password: ps123456
driver-class-name: com.mysql.jdbc.Driver
eureka:
instance:
prefer-ip-address: true
hostname: localhost
client:
register-with-eureka: true
fetch-registry: false
service-url:
defaultZone: http://localhost:8761/eureka/
mapper包下的 UserMapper.java:
// 根據賬戶和密碼查詢mysql資料庫中user表的資訊
@Mapper
public interface UserMapper {
@Select("select * from user where user=#{userName} and authentication_string=password(#{password})")
public List<User> queryUser(@Param("userName") String userName, @Param("password")String password);
}
entity包下的User.java實體類:
@Data
@NoArgsConstructor
public class User {
private String userName;
private String password;
}
解釋:
[email protected]註解:生成屬性的set,get方法
[email protected]註解:生成構造方法
entity包下的Result.java 實體類:
// 要返回的實體類
@Data
@NoArgsConstructor
public class Result {
private int code;
private String msg;
private List data;
}
controller包下的UserController.java:
@RestController
public class UserController {
@Autowired
UserMapper usermapper;
@PostMapping("/validateUser")
public Result validateUser(@RequestBody User user){
List<User> maps = usermapper.queryUser(user.getUserName(), user.getPassword());
// 將獲得的資料經過邏輯驗證返回給介面微服務的控制層
Result re = new Result();
if(maps.size()>0){
re.setCode(1);
re.setMsg("請輸入正確的使用者名稱和密碼");
}
return re;
}
}
解釋:
[email protected]的作用就相當於@[email protected]的結合體
[email protected]:掃描控制層
[email protected]:表示返回的型別是個JSON資料
[email protected]: 接收客戶端傳來的資料
3.SPRINGCLOUD_USERUI模組
首先在pom.xml匯入依賴:
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.18</version>
<scope>provided</scope>
</dependency>
</dependencies>
application.yml資原始檔:
#介面一般是80埠
server:
port: 80
#給登入微服務設定一個名字
spring:
application:
name: userui
eureka:
instance:
prefer-ip-address: true
hostname: localhost
client:
register-with-eureka: true
fetch-registry: true
service-url:
defaultZone: http://localhost:8761/eureka/
com.ps包下的UserUi.java:
@SpringBootApplication
// 啟用eureka的客戶端
@EnableEurekaClient
public class UserUi {
@Bean
// 支援負載均衡功能
@LoadBalanced
public RestTemplate restTemplate(){
return new RestTemplate();
}
public static void main(String[] args) {
new SpringApplicationBuilder(UserUi.class).web(true).run(args);
}
}
entity包下的User.java:
@Data
@NoArgsConstructor
public class User {
private String userName;
private String password;
}
Result.java:
@Data
@NoArgsConstructor
public class Result {
private int code;
private String msg;
private List data;
}
controller包下的UserController.java:
@Controller
public class UserController {
@Autowired
RestTemplate restTemplate;
@PostMapping("/rlogin")
public String rlogin(User user){
// 需要呼叫userservice這個微服務,註冊中心裡面服務名是大寫
// validateUser:指要轉跳的微服務的控制層的路徑
String url = "http://USERSERVICE/validateUser";
// user:將user獲取的資料傳到微服務
// Result.class:指微服務返回的型別
ResponseEntity<Result> objectResponseEntity = restTemplate.postForEntity(url,user ,Result.class);
Result body = objectResponseEntity.getBody();
// 當重微服務得到的Result物件的資料中code屬性是1時表示,登入成功
if(body.getCode()==1){
return "redirect:/suc.html";
}else{
return "redirect:/login.html";
}
}
}
解釋:@Controller:指定返回的html介面,必須是重定向轉跳
login.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!--這裡是登入介面-->
<form method="post" action="rlogin">
<label>使用者名稱</label>
<input name="userName"/><br>
<label>密 碼</label>
<input name="password"/><br>
<input type="submit" value="登入"/>
</form>
</body>
</html>
suc.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!--登入成功展示-->
登入成功
</body>
</html>
三.效果展示
1.依次執行SPRINGCLOUD_EUREKASERVER(註冊中心),SPRINGCLOUD_USERSERVICE(微服務),SPRINGCLOUD_USERUI(客戶端)
2.去註冊中心檢視微服務:http://localhost:8761/
瀏覽登入介面:
輸入賬戶和密碼登入後: