关于springcloud实现服务之间调用
程序员文章站
2022-10-03 18:09:15
关于springcloud实现服务之间调用创建父工程、任意名字创建子项目grade-euraka目录结构如下图pom.xml加入依赖
关于springcloud实现服务之间调用
本文使用euraka搭建,实现服务者与消费者之间的调用
数据库脚本以及源码地址
链接:https://pan.baidu.com/s/1tyy-yzTN_l44R-OQoyGDWQ
提取码:8nkv
第一步创建数据库grade并建表student
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
`id` bigint(0) NOT NULL AUTO_INCREMENT,
`sname` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`sno` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 9 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of student
-- ----------------------------
INSERT INTO `student` VALUES (1, '张无忌', '001');
INSERT INTO `student` VALUES (2, '李亦非', '002');
INSERT INTO `student` VALUES (3, '小古', '003');
INSERT INTO `student` VALUES (4, '陈丽', '004');
INSERT INTO `student` VALUES (5, '王邱村', '005');
INSERT INTO `student` VALUES (6, '测试', '004');
INSERT INTO `student` VALUES (7, '莫', '009');
INSERT INTO `student` VALUES (8, '周芷若', '008');
SET FOREIGN_KEY_CHECKS = 1;
创建父工程、任意名字
创建子项目
euraka01目录结构如下图
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>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.qinheyou</groupId>
<artifactId>eureka01</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>eureka01</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<spring-cloud.version>Hoxton.SR6</spring-cloud.version>
</properties>
<dependencies>
<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>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
application.yml配置文件信息
server:
## 端口号
port: 20001
spring:
application:
##定义服务名称
name: eureka01
eureka:
client:
service-url:
## 注册地址
defaultZone: http://127.0.0.1:${server.port}/eureka
####因为自己是注册中心,是否需要将自己注册给自己的注册中心(集群的时候是需要是为true),不加默认注册自己
register-with-eureka: false
###因为自己是注册中心, 不需要去检索服务信息
fetch-registry: false
启动类Eureka01Application
package com.qinheyou.euraka;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
@SpringBootApplication
@EnableEurekaServer // 声明当前springboot应用是一个eureka服务中心
public class Euraka01Application {
public static void main(String[] args) {
SpringApplication.run(Euraka01Application.class, args);
}
}
注册中心配置完成了
下面是我们的提供者provider01
目录结构如下
第一步依旧是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>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.qinheyou</groupId>
<artifactId>provider01</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>provider01</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.3</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
<version>2.0.4</version>
</dependency>
<!-- Eureka客户端 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<!-- Swagger starter-->
<dependency>
<groupId>com.spring4all</groupId>
<artifactId>swagger-spring-boot-starter</artifactId>
<version>1.8.0.RELEASE</version>
</dependency>
<!-- Swagger ui-->
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-models</artifactId>
<version>1.5.21</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>javax.persistence-api</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
<version>1.0</version>
</dependency>
<!--hibernate-->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.0.7.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.netflix.hystrix/hystrix-javanica -->
<dependency>
<groupId>com.netflix.hystrix</groupId>
<artifactId>hystrix-javanica</artifactId>
<version>1.5.12</version>
</dependency>
</dependencies>
<!-- SpringCloud的依赖 -->
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Hoxton.SR5</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
application.yml
server:
###会员服务启动端口号
port: 20002
spring:
application:
### 服务名称(注意,这里对应的是消费者StudentClient接口中的value属性 :@FeignClient(value = "provider01"))
name: provider01
main:
allow-bean-definition-overriding: true
logging:
level:
root: info
org.springframework: info
profiles:
active: '@profiles.active@'
datasource:
url: jdbc:mysql://localhost:3306/grade?serverTimezone=GMT%2B8
## 这里是数据库名称,
username: root
## 这里是你的数据库密码,要改一下哦
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
jpa:
hibernate:
ddl-auto: update
show-sql: true
mybatis:
type-aliases-package: com.qinheyou,provider.entity
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:20001/eureka
实体类Student
package com.qinheyou.provider.entity;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.swagger.annotations.ApiModel;
import javax.persistence.*;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
/**
* @program: grade-service-provider
* @author: Mr.Mo
* @create: 2020-07-11 16:45
**/
@Entity
@Table(name = "student")
@ApiModel(value="学生表",description = "这是学生表")
@JsonIgnoreProperties(value = { "hibernateLazyInitializer"})
public class Student implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
// 学生姓名
@Column(name = "sname")
private String sname;
// 学生学号
@Column(name = "sno")
private String sno;
//targetEntity属性表示默认关联的实体类型,默认为当前标注的实体类;
//cascade属性表示与此实体一对一关联的实体的联级样式类型。联级样式上当对实体进行操作时的策略。
//·CascadeType.PERSIST (级联新建)
//·CascadeType.REMOVE (级联删除)
//·CascadeType.REFRESH (级联刷新)
//·CascadeType.MERGE (级联更新)中选择一个或多个。
//·还有一个选择是使用CascadeType.ALL ,表示选择全部四项
//fetch属性是该实体的加载方式,有两种:LAZY和EAGER。
//optional属性表示关联的实体是否能够存在null值。默认为true,表示可以存在null值。如果为false,则要同时配合使用@JoinColumn标记。
//mappedBy属性用于双向关联实体时,标注在不保存关系的实体中。
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public String getSno() {
return sno;
}
public void setSno(String sno) {
this.sno = sno;
}
}
mapper
package com.qinheyou.provider.mapper;
import com.qinheyou.provider.entity.Student;
import org.apache.ibatis.annotations.Mapper;
import tk.mybatis.mapper.common.BaseMapper;
@Mapper
public interface StudentMapper extends BaseMapper<Student> {
}
service
package com.qinheyou.provider.service;
import com.qinheyou.provider.entity.Student;
import com.qinheyou.provider.mapper.StudentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* @program: grade-service-provider
* @author: Mr.M
* @create: 2020-07-14
**/
@Service
public class StudentService {
// @Autowired
// private StudentDao studentDao;
@Autowired
private StudentMapper studentMapper;
public Student queryById(Long id) {
return this.studentMapper.selectByPrimaryKey(id);
}
}
controller
package com.qinheyou.provider.contronller;
import com.qinheyou.provider.entity.Student;
import com.qinheyou.provider.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("student/")
@CrossOrigin
public class StudentController {
@Autowired
private StudentService studentService;
/**
* @Author: M
* @Description: 根据id查询,此方法调用mybatis实现
* @DateTime: 2020/7/14
* @Params: [id]
* @Return cn.grade.service.entity.Student
*/
// 访问地址
// http://localhost:20002/student/getByid/5
@GetMapping("getByid/{id}")
public Student queryById(@PathVariable("id") Long id) {
return this.studentService.queryById(id);
}
}
启动类Provider01Application
package com.qinheyou.provider;
import com.spring4all.swagger.EnableSwagger2Doc;
import org.springframework.boot.SpringApplication;
import org.springframework.cloud.client.SpringCloudApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
@SpringCloudApplication
@EnableDiscoveryClient
@EnableJpaRepositories
@EnableSwagger2Doc
public class Provider01Application {
public static void main(String[] args) {
SpringApplication.run(Provider01Application.class, args);
}
}
提供者完成,接下是消费者member01
目录结构
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>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.qinheyou</groupId>
<artifactId>member01</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>member01</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<spring-cloud.version>Hoxton.SR5</spring-cloud.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>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<!-- Swagger starter-->
<dependency>
<groupId>com.spring4all</groupId>
<artifactId>swagger-spring-boot-starter</artifactId>
<version>1.8.0.RELEASE</version>
</dependency>
<!-- Swagger ui-->
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-models</artifactId>
<version>1.5.21</version>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
application.yml
server:
port: 20003
spring:
application:
name: member01
eureka:
client:
service-url:
defaultZone: http://localhost:20001/eureka
实体类Student
package com.qinheyou.member.entity;
/**
* @program: grade-service-provider
* @author: Mr.Mo
* @create: 2020-07-11 18:23
**/
public class Student {
private static final long serialVersionUID = 1L;
private Long id;
// 学生姓名
private String sname;
// 学生学号
private String sno;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public String getSno() {
return sno;
}
public void setSno(String sno) {
this.sno = sno;
}
}
StudentClient
package com.qinheyou.member.client;
import com.qinheyou.member.entity.Student;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* @program: grade-service-provider
* @author: Mr.Mo
* @create: 2020-07-11 18:21
**/
// 注意,这里value属性对应的是提供者的服务名称
@FeignClient(value = "provider01") // 标注该类是一个feign接口
public interface StudentClient {
@GetMapping(value = "student/getByid/{id}")
@ResponseBody
Student getStudent(@PathVariable("id") Long id);
}
StudentController
package com.qinheyou.member.contronller;
import com.qinheyou.member.client.StudentClient;
import com.qinheyou.member.entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
/**
* @program: grade-service-provider
* @author: Mr.Mo
* @create: 2020-07-11 18:22
**/
@RestController
@RequestMapping("consumer/")
@CrossOrigin
public class StudentController {
@Autowired
private StudentClient client;
//consumer/getByid/1
@GetMapping("getByid/{id}")
public Student getStudent(@PathVariable("id") Long id ) {
Student student = client.getStudent(id);
System.out.println("输出:"+student);
System.out.println("姓名:"+student.getSname());
return student;
}
}
启动类Member01Application
package com.qinheyou.member;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;
@SpringBootApplication
@EnableFeignClients
public class Member01Application {
public static void main(String[] args) {
SpringApplication.run(Member01Application.class,args);
}
}
接下来打开浏览器测试
按图片上面步骤
访问地址 http://localhost:20001
2
3
修改路径地址
http://localhost:20002/student/getByid/5
4
查询成功后,实现调用
5
更改路径
http://localhost:20003/consumer/getByid/1
有问题请留言,.
本文地址:https://blog.csdn.net/a19994454401/article/details/107472584
上一篇: Java笔试题
推荐阅读
-
Python 实现两个服务器之间文件的上传方法
-
Shell脚本实现线上服务器之间对比文件是否一致
-
[Spring cloud 一步步实现广告系统] 11. 使用Feign实现微服务调用
-
SpringCloud微服务(04):Turbine组件,实现微服务集群监控
-
关于实现今天到一年中任意一天两者之间的天数差的计算
-
跟我学SpringCloud | 第三篇:服务的提供与Feign调用
-
关于递归调用,实现树形菜单的样式
-
Java开发之使用websocket实现web客户端与服务器之间的实时通讯
-
(springCloud-8 Zuul网关路由的基本配置feign实现接口调用)
-
Spring Cloud下使用Feign Form实现微服务之间的文件上传