(注:以maven聚合工程的方式创建项目)
项目路径:https://github.com/JiangHuaiChuan/HQL.git
0.创建父工程pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>springcloud</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springcloud</name>
<packaging>pom</packaging>
<modules>
<module>eurekaserver</module>
<module>getway</module>
<module>app1</module>
</modules>
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencyManagement>
<dependencies>
<!--spring boot 2.3.3-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>2.3.12.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!--spring cloud Hoxton.SR8-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Hoxton.SR12</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!--spring cloud alibaba 2.1.0.RELEASE-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>2.1.0.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<skip>true</skip>
<fork>true</fork>
<addResources>true</addResources>
</configuration>
</plugin>
</plugins>
</build>
</project>
1.创建注册中心eureka
1.1注册中心pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.example</groupId>
<artifactId>springcloud</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>eurekaserver</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>eurekaserver</name>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
1.2注册中心配置
server:
port: 9080
eureka:
instance:
hostname: eureka-server
client:
service-url:
defaultZone: http://127.0.0.1:9080/eureka
register-with-eureka: false
1.3注册中心启动类
package com.example.eurekaserver;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
@SpringBootApplication
@EnableEurekaServer
public class EurekaserverApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaserverApplication.class, args);
}
}
2.创建网关子工程
2.1网关子工程pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.example</groupId>
<artifactId>springcloud</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>getway</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>getway</name>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>8</source>
<target>8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
2.2网关子工程配置
server:
port: 8080
spring:
application:
name: gateway
cloud:
gateway:
discovery:
locator:
enabled: false #开启自动代理
lowerCaseServiceId: true
# routes:
# -id: path_route1
# uri: http://127.0.0.1:8081/app1/getAppName
# predicates:
# -Path=/app1gna
# filters:
# - StripPrefix=1
# - AddResponseHeader=X-Response-Default-Foo, Default-Bar
eureka:
instance:
statusPageUrlPath: /actuator/info
healthCheckUrlPath: /actuator/health
home-page-url-path: /
ip-address: 127.0.0.1 #决定Eureka服务显示host
hostname: ${eureka.instance.ip-address} #决定服务跳转host,必须指定
prefer-ip-address: false #不设可自己指定,true会自动获取本地ipv4地址
instance-id: ${eureka.instance.ip-address}:${spring.application.name}:${server.port}
client:
service-url:
defaultZone: http://127.0.0.1:9080/eureka/
2.3网关子工程主启动类
package com.example.getway;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@SpringBootApplication
@EnableEurekaClient
public class GetwayApplication {
public static void main(String[] args) {
SpringApplication.run(GetwayApplication.class, args);
}
}
2.4网关子工程路由规则
package com.example.getway.routbean;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.RequestPredicates;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerResponse;
@Configuration
public class RoutBean {
@Bean
public RouterFunction<ServerResponse> testFunRouterFunction() {
RouterFunction<ServerResponse> route = RouterFunctions.route(
RequestPredicates.path("/test"),
request -> ServerResponse.ok().body(BodyInserters.fromObject("I am testing")));
return route;
}
@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
return builder.routes()
.route("path_route0", r -> r.path("/app1/**").uri("http://127.0.0.1:8081"))
.route("path_route1", r -> r.path("/s").uri("https://www.baidu.com"))
.build();
}
}
3.创建应用子工程
3.1应用子工程pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.example</groupId>
<artifactId>springcloud</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>app1</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>app1</name>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
<!--mysql依赖-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.23</version>
<scope>runtime</scope>
</dependency>
<!--MyBatis-Plus (简称 MP)是一个 MyBatis 的增强工具,
在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.2.0</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>3.2.0</version>
</dependency>
<!--数据库连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>8</source>
<target>8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
3.2应用子工程配置
server:
port: 8081
spring:
application:
name: app1
#数据库链接信息
datasource:
druid:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3307/springcloud?useSSL=false&serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8
username: root
password: password
initial-size: 1
min-idle: 1
max-active: 20
test-on-borrow: true
eureka:
instance:
statusPageUrlPath: /actuator/info
healthCheckUrlPath: /actuator/health
home-page-url-path: /
ip-address: 127.0.0.1 #决定Eureka服务显示host
hostname: ${eureka.instance.ip-address} #决定服务跳转host,必须指定
prefer-ip-address: false #不设可自己指定,true会自动获取本地ipv4地址
instance-id: ${eureka.instance.ip-address}:${spring.application.name}:${server.port}
client:
service-url:
defaultZone: http://127.0.0.1:9080/eureka/
3.3应用子工程主启动类
package com.example.app1;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@SpringBootApplication
@EnableEurekaClient
@EnableCircuitBreaker
public class App1Application {
public static void main(String[] args) {
SpringApplication.run(App1Application.class, args);
}
}
3.4应用子工程控制层
package com.example.app1.controller;
import com.example.app1.bean.dto.ResponseCode;
import com.example.app1.bean.dto.Result;
import com.example.app1.bean.dmo.Student;
import com.example.app1.service.StudentService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/app1")
public class App1_1Controller {
@Autowired
private StudentService studentService;
@RequestMapping("/getAppName")
public String getAppName() {
return "app1";
}
@PostMapping("/getStuById")
@HystrixCommand(fallbackMethod = "errorCallBack")//模仿没有这个数据时,服务降级
public Object getStuById(@RequestBody Student studentT) {
Student student = studentService.getStuById(studentT.getId());
if (student == null) {
throw new RuntimeException("未查询到该用户");
}
return new Result(ResponseCode.SUCCESS, student);
}
@PostMapping("/getAllStu")
public Object getAllStu() {
List list = studentService.getAllStu();
if (list == null) {
return new Result(ResponseCode.FAIL_900, "未查询到用户");
}
return new Result(ResponseCode.SUCCESS, list);
}
//指定一个降级的方法
public Object errorCallBack(@RequestBody Student studentT) {
return new Result(ResponseCode.FAIL_900, "用户" + studentT.getId() + "不存在");
}
}
3.5应用子工程service层
package com.example.app1.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.app1.bean.dmo.Student;
import com.example.app1.dao.StudentDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class StudentService {
@Autowired
private StudentDao studentDao;
public Student getStuById(String id) {
return studentDao.getStuById(id);
}
public List<Student> getAllStu() {
return studentDao.list(
new LambdaQueryWrapper<Student>().like(Student::getId, "1")
);
}
}
3.6应用子工程dao、mapper层
package com.example.app1.dao;
import com.baomidou.mybatisplus.extension.service.IService;
import com.example.app1.bean.dmo.Student;
public interface StudentDao extends IService<Student> {
Student getStuById(String id);
}
package com.example.app1.dao.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.app1.bean.dmo.Student;
import com.example.app1.dao.StudentDao;
import com.example.app1.mapper.StudentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
@Repository
public class StudentDaoImpl extends ServiceImpl<StudentMapper, Student> implements StudentDao {
@Autowired
private StudentMapper studentMapper;
public Student getStuById(String id){
return studentMapper.selectById(id);
}
}
package com.example.app1.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.app1.bean.dmo.Student;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface StudentMapper extends BaseMapper<Student> {
}
3.7DMO与DTO
package com.example.app1.bean.dmo;
import lombok.Data;
import org.springframework.stereotype.Component;
import java.io.Serializable;
@Component
@Data
public class Student implements Serializable {
private String id;
private String name;
private String sex;
private Integer age;
}
package com.example.app1.bean.dto;
public enum ResponseCode {
SUCCESS(200, "成功"),
FAIL_900(900, "失败"),
FAIL_901(901, "传入数据异常");
private int code;
private String message;
ResponseCode(int code, String message) {
this.code = code;
this.message = message;
}
public int getCode() {
return code;
}
public String getMessage() {
return message;
}
}
package com.example.app1.bean.dto;
import lombok.Data;
import org.springframework.stereotype.Component;
@Data
@Component
public class Result {
private int code;
private String message;
private Object data;
public Result() {
}
public Result(ResponseCode responseCode) {
this.code = responseCode.getCode();
this.message = responseCode.getMessage();
this.data = "";
}
public Result(ResponseCode responseCode, String message) {
this.code = responseCode.getCode();
this.message = message;
this.data = "";
}
public Result(ResponseCode responseCode, Object data) {
this.code = responseCode.getCode();
this.message = responseCode.getMessage();
this.data = data;
}
public Result(ResponseCode responseCode, String message, Object data) {
this.code = responseCode.getCode();
this.message = message;
this.data = data;
}
}
4.项目结构
5.运行效果
5.1注册中心
5.2应用子工程
5.3网关服务
6.执行SQL
CREATE SCHEMA `springcloud`;
USE springcloud;
CREATE TABLE `student`
(
`id` char(10) NOT NULL,
`name` varchar(45) NOT NULL,
`sex` char(1) NOT NULL,
`age` int NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
----有时间继续完善----
补充远程调用openfeign,见github