1.微服务场景模拟
1.1 创建父工程
1. 首先打开spring,如下图
2. 创建一个java working setting。
3. 创建一个父工程,打包方式为pom,pom文件如下:
<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.zpark.springcould</groupId>
<artifactId>microservicecloud</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>pom</packaging>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.11.RELEASE</version>
<relativePath />
</parent>
<properties>
<spring-cloud.version>Hoxton.SR5</spring-cloud.version>
<junit.version>4.12</junit.version>
<log4j.version>1.2.17</log4j.version>
<java.version>1.8</java.version>
<lombok.version>1.16.18</lombok.version>
<mapper.starter.version>2.1.5</mapper.starter.version>
<mysql.version>5.1.46</mysql.version>
<druid.version>1.1.16</druid.version>
<mybatis.spring.boot.version>1.3.0</mybatis.spring.boot.version>
</properties>
<dependencyManagement>
<dependencies>
<!-- springCloud -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!-- 通用Mapper启动器 -->
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
<version>${mapper.starter.version}</version>
</dependency>
<!-- mysql驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<modules>
<module>comsumer-demo</module>
</modules>
</project>
4. 点击父类新建一个maven-module,对外提供查询用户的服务,打包方式jar,结构如下:
5. 其pom文件:
<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.zpark.springcould</groupId>
<artifactId>microservicecloud</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>user-service-9091</artifactId>
<properties>
<maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>
</properties>
<dependencies>
<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>
<scope>test</scope>
</dependency>
<!-- 通用Mapper启动器 -->
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
</dependency>
<!-- mysql驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies>
</project>
6. 创建数据库
/*
Navicat Premium Data Transfer
Source Server : localhost_3306
Source Server Type : MySQL
Source Server Version : 50045
Source Host : localhost:3306
Source Schema : myspringcould
Target Server Type : MySQL
Target Server Version : 50045
File Encoding : 65001
Date: 17/08/2021 09:45:33
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for tb_user
-- ----------------------------
DROP TABLE IF EXISTS `tb_user`;
CREATE TABLE `tb_user` (
`id` bigint(20) NOT NULL DEFAULT '',
`user_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`password` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`age` int(11) NULL DEFAULT NULL,
`sex` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`birthday` datetime NULL DEFAULT NULL,
`created` datetime NULL DEFAULT NULL,
`updated` datetime NULL DEFAULT NULL,
`note` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
PRIMARY KEY USING BTREE (`id`)
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;
-- ----------------------------
-- Records of tb_user
-- ----------------------------
INSERT INTO `tb_user` VALUES (1, 'yzre', 'yzre123', '伊泽瑞尔', 18, '1', '2021-05-12 16:20:29', '2021-05-05 16:20:39', '2021-05-05 16:20:44', NULL);
INSERT INTO `tb_user` VALUES (2, 'llfs', 'llfs123', '流浪法师', 18, '1', '2021-05-04 16:21:26', '2021-05-05 16:21:42', '2021-05-05 16:21:46', NULL);
INSERT INTO `tb_user` VALUES (3, 'klst', 'klst123', '卡莉斯塔', 18, '2', '2021-05-02 16:23:10', '2021-05-12 16:23:16', '2021-05-12 16:23:21', NULL);
INSERT INTO `tb_user` VALUES (4, 'ks', 'ks123', '卡莎', 18, '2', '2021-05-05 16:24:52', '2021-05-06 16:24:58', '2021-05-06 16:25:04', NULL);
INSERT INTO `tb_user` VALUES (5, 'flezd', 'flezd123', '弗雷尔卓德', 18, '1', '2021-05-07 16:25:46', '2021-05-08 16:25:52', '2021-05-08 16:25:57', NULL);
INSERT INTO `tb_user` VALUES (6, 'jks', 'jks123', '金克丝', 18, '2', '2021-05-10 16:27:28', '2021-05-11 16:27:35', '2021-05-11 16:27:39', NULL);
SET FOREIGN_KEY_CHECKS = 1;
7. 编写实体类
package com.zpark.user.entities;
import java.util.Date;
import javax.persistence.Id;
import javax.persistence.Table;
import tk.mybatis.mapper.annotation.KeySql;
@Table(name="tb_user")
public class User {
@Id
@KeySql(useGeneratedKeys = true) // 开启主键自动回填
private Long id;
private String userName;
private String password;
private String name;
private Integer age;
private Integer sex;
private Date birthday;
private Date created;
private Date updated;
private String note;
public User() {
super();
}
public User(Long id, String userName, String password, String name, Integer age, Integer sex, Date birthday,
Date created, Date updated, String note) {
super();
this.id = id;
this.userName = userName;
this.password = password;
this.name = name;
this.age = age;
this.sex = sex;
this.birthday = birthday;
this.created = created;
this.updated = updated;
this.note = note;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Integer getSex() {
return sex;
}
public void setSex(Integer sex) {
this.sex = sex;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public Date getUpdated() {
return updated;
}
public void setUpdated(Date updated) {
this.updated = updated;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
@Override
public String toString() {
return "User [id=" + id + ", userName=" + userName + ", password=" + password + ", name=" + name + ", age="
+ age + ", sex=" + sex + ", birthday=" + birthday + ", created=" + created + ", updated=" + updated
+ ", note=" + note + "]";
}
}
注意:lombok(小辣椒) 导致 springmvc 使用 @RequestBody注解 接收 json数据 对象参数绑定失败。
8. 编写启动类,注意启动类的位置。
package com.zpark.user;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import tk.mybatis.spring.annotation.MapperScan;
@SpringBootApplication
@MapperScan("com.zpark.user.mapper")
public class UserApplication {
public static void main(String[] args) {
SpringApplication.run(UserApplication.class, args);
}
}
9. 整合mybatis
- 创建UserMapper接口继承Mapper接口(需要到启动类添加扫描注解MapperScan)
package com.zpark.user.mapper;
import org.springframework.stereotype.Repository;
import com.zpark.user.entities.User;
import tk.mybatis.mapper.common.Mapper;
@Repository
public interface UserMapper extends Mapper<User>{
}
- MyBatis整合数据源:创建application.yml
server:
port: 9091
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/myspringcould
username: root
password: 123456
mybatis:
type-aliases-package: com.zpark.user.entities
10. 创建测试类
package com.zpark.user;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.zpark.user.entities.User;
import com.zpark.user.mapper.UserMapper;
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserServiceApplicationTests {
@Autowired
UserMapper userMapper;
@Test
public void testUser() {
User user = userMapper.selectByPrimaryKey(1);
System.out.println(user);
}
}
11. 创建Service层
- 创建UserService接口
package com.zpark.user.service;
import com.zpark.user.entities.User;
public interface UserService {
User queryById(Long id);
}
- 创建UserServiceImpl实现类
package com.zpark.user.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zpark.user.entities.User;
import com.zpark.user.mapper.UserMapper;
import com.zpark.user.service.UserService;
@Service
public class UserServiceImpl implements UserService{
@Autowired
UserMapper userMapper;
@Override
public User queryById(Long id) {
return userMapper.selectByPrimaryKey(id);
}
}
12. 创建Controller层
package com.zpark.user.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import com.zpark.user.entities.User;
import com.zpark.user.service.UserService;
@RestController
public class UserController {
@Autowired
UserService userService;
@GetMapping("/user/{id}")
public User queryById(@PathVariable("id")Long id) {
User user = userService.queryById(id);
System.out.println(user);
return user;
}
}
13. 测试
http://localhost:9091/user/3
1.2 服务调用者
1.在父类项目新建一个Maven-module,调用服务提供者的查询服务,结构如下:
2.pom文件,消费者是调用的上一个服务提供者,本身不需要与数据库交互。
<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.zpark.springcould</groupId>
<artifactId>microservicecloud</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>comsumer-demo</artifactId>
<properties>
<maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
</project>
3.实体类
服务消费者拿过来的数据需要封装,创建实体类User,只需要封装数据,不需要进行数据库连接,不需要加注解。
package com.zpark.consumer.entities;
import java.util.Date;
public class User {
private Long id;
private String userName;
private String password;
private String name;
private Integer age;
private Integer sex;
private Date birthday;
private Date created;
private Date updated;
private String note;
public User() {
super();
}
public User(Long id, String userName, String password, String name, Integer age, Integer sex, Date birthday,
Date created, Date updated, String note) {
super();
this.id = id;
this.userName = userName;
this.password = password;
this.name = name;
this.age = age;
this.sex = sex;
this.birthday = birthday;
this.created = created;
this.updated = updated;
this.note = note;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Integer getSex() {
return sex;
}
public void setSex(Integer sex) {
this.sex = sex;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public Date getUpdated() {
return updated;
}
public void setUpdated(Date updated) {
this.updated = updated;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
@Override
public String toString() {
return "User [id=" + id + ", userName=" + userName + ", password=" + password + ", name=" + name + ", age="
+ age + ", sex=" + sex + ", birthday=" + birthday + ", created=" + created + ", updated=" + updated
+ ", note=" + note + "]";
}
}
4.启动类
- 交给容器的注解是@Bean
- RestTemplate:提供远程调用服务。
package com.zpark.consumer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
public class ComsumerApplication {
public static void main(String[] args) {
SpringApplication.run(ComsumerApplication.class, args);
}
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
5.编写controller类
注意添加@ReatController注解
package com.zpark.consumer.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import com.zpark.consumer.entities.User;
@RestController
public class UserController {
@Autowired
private RestTemplate restTemplate;
//produces = "application/json;charset=utf-8":json数据格式转换,编码转换。
//produces:指定响应体返回类型和编码。
@GetMapping("/comuser/{id}")
public User findById(@PathVariable("id")Long id) {
String url = "http://localhost:9091/user/"+id;
return restTemplate.getForObject(url, User.class);//访问url,返回的数据用User去承接。
}
}
6.测试
http://localhost:8080/comuser/2