参考源码https://codeload.github.com/acloudyh/springCloud/zip/master
建立一个父工程,下面总共有五个服务,两个Eureka服务,两个支付服务,一个订单服务。
每个服务都是一个独立的springboot项目。
要达到的效果是,支付中心为订单中心提供服务,订单中心通过注册中心获取服务,调用支付功能。
访问http://eureka7002.com:7002/ 看到的页面如下:
通过postman请求订单中心接口,看到的结果如下
由于加了负载均衡,会交替请求8001和8002的服务
重点看配置文件
一、建立父工程
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
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.george.springcloud</groupId>
<artifactId>springCloud</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>pom</packaging>
<modules>
<module>cloud-provider-payment8001</module>
<module>cloud-consumer-order80</module>
<module>cloud-api-commons</module>
<module>cloud-eureka-server7001</module>
<module>cloud-eureka-server7002</module>
<module>cloud-provider-payment8002</module>
<module>cloud-provider-payment8004</module>
<module>cloud-consumerzk-order80</module>
<module>cloud-providerconsul-payment8006</module>
<module>cloud-consumerconsul-order80</module>
<module>cloud-consumer-feign-order80</module>
<module>cloud-provider-hystrix-payment8001</module>
<module>cloud-consumer-feign-hystrix-order80</module>
<module>cloud-consumer-hystrix-dashboard9001</module>
<module>cloud-gateway-gateway9527</module>
<module>cloud-config-center-3344</module>
<module>cloud-config-client-3355</module>
<module>cloud-config-client-3366</module>
<module>cloud-stream-rabbitmq-provider8801</module>
<module>cloud-stream-rabbitmq-consumer8802</module>
<module>cloud-stream-rabbitmq-consumer8803</module>
<module>cloudalibaba-provider-payment9001</module>
<module>cloudalibaba-provider-payment9002</module>
<module>cloudalibaba-consumer-nacos-order83</module>
<module>cloudalibaba-config-nacos-client3377</module>
<module>cloudalibaba-sentinel-service8401</module>
<module>cloudalibaba-provider-payment9003</module>
<module>cloudalibaba-provider-payment9004</module>
<module>cloudalibaba-consumer-nacos-order84</module>
<module>seata-order-service2001</module>
<module>seata-order-service2002</module>
<module>seata-order-service2003</module>
</modules>
<!-- 统一管理jar包版本 -->
<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>
<mysql.version>5.1.47</mysql.version>
<druid.version>1.1.21</druid.version>
<mybatis.spring.boot.version>1.3.0</mybatis.spring.boot.version>
</properties>
<!-- 子模块继承之后,提供作用:锁定版本+子modlue不用写groupId和version -->
<dependencyManagement>
<dependencies>
<!--spring boot 2.2.2-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>2.2.2.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!--spring cloud Hoxton.SR1-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Hoxton.SR1</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>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>${druid.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>${mybatis.spring.boot.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<fork>true</fork>
<addResources>true</addResources>
</configuration>
</plugin>
</plugins>
</build>
</project>
一、搭建一个Eureka集群
EurekaMain7001
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>springCloud</artifactId>
<groupId>com.george.springcloud</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>cloud-eureka-server7001</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
<!-- 引入自定义的api通用包,可以使用Payment支付Entity -->
<dependency>
<groupId>com.george.springcloud</groupId>
<artifactId>cloud-api-commons</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<!-- boot web actuator -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
</dependencies>
</project>
server:
port: 7001
eureka:
instance:
#eureka服务端的实例名称
hostname: eureka7001.com
client:
#false表示不向注册中心注册自己
register-with-eureka: false
#false表示自己端就是注册中心,职责是维护实例,并不需要检索服务
fetch-registry: false
service-url:
#设置与Eureka Server 交互的地址查询服务和注册服务都需要依赖这个地址
# defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
defaultZone: http://eureka7002.com:7002/eureka/ #集群指向其他eureka
server:
# 关闭自我保护机制,保证不可用服务被及时剔除.默认开启保护机制 true
enable-self-preservation: false
eviction-interval-timer-in-ms: 2000
package com.george.springcloud;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
/**
* @author Yang Hao
* @description
* @date 2020-09-14 21:47
*/
@SpringBootApplication
@EnableEurekaServer
public class EurekaMain7001 {
public static void main(String[] args) {
SpringApplication.run(EurekaMain7001.class, args);
}
}
EurekaMain7002
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>springCloud</artifactId>
<groupId>com.george.springcloud</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>cloud-eureka-server7002</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
<!-- 引入自定义的api通用包,可以使用Payment支付Entity -->
<dependency>
<groupId>com.george.springcloud</groupId>
<artifactId>cloud-api-commons</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<!-- boot web actuator -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
</dependencies>
</project>
server:
port: 7002
eureka:
instance:
#eureka服务端的实例名称
hostname: eureka7002.com
client:
#false表示不向注册中心注册自己
register-with-eureka: false
#false表示自己端就是注册中心,职责是维护实例,并不需要检索服务
fetch-registry: false
service-url:
#设置与Eureka Server 交互的地址查询服务和注册服务都需要依赖这个地址
# defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
defaultZone: http://eureka7001.com:7001/eureka/ #集群指向其他eureka
server:
# 关闭自我保护机制,保证不可用服务被及时剔除.默认开启保护机制 true
enable-self-preservation: false
eviction-interval-timer-in-ms: 2000
package com.george.springcloud;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
/**
* @author Yang Hao
* @description
* @date 2020-09-14 21:47
*/
@SpringBootApplication
@EnableEurekaServer
public class EurekaMain7002 {
public static void main(String[] args) {
SpringApplication.run(EurekaMain7002.class, args);
}
}
注意:需要修改C:\Windows\System32\drivers\etc\hosts
127.0.0.1 eureka7001.com
127.0.0.1 eureka7002.com
搭建支付中心集群
PaymentMain8001
application.yml
server:
port: 8001
spring:
application:
name: cloud-payment-service
datasource:
#当前数据源操作类型
type: com.alibaba.druid.pool.DruidDataSource
#mysql驱动包
driver-class-name: org.gjt.mm.mysql.Driver
url: jdbc:mysql://localhost:3306/cloud2020?useUnicode=true&characterEncoding=utf8&useSSL=false
username: root
password: 123456
# #P94 需要的配置
# zipkin:
# base-url: http://localhost:9411
# sleuth:
# sampler:
# probability: 1 #采样率值介于0-1之间,1标识全部采集
mybatis:
mapperLocations: classpath:mapper/*.xml
#所有entity别名类所在包
type-aliases-package: com.george.springcloud.entities
eureka:
client:
#是否将自己注册到注册中心, 默认true
register-with-eureka: true
#是否从EurekaServer抓取已有的注册信息,单机无所谓,集群必须设置为true配合ribbon使用负载均衡
fetch-registry: true
service-url:
# defaultZone: http://localhost:7001/eureka #单机版
defaultZone: http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka #集群版
instance:
instance-id: payment8001
#访问路径可以显示IP地址
prefer-ip-address: true
#Eureka客户端向服务端发送心跳的时间间隔.单位为秒(默认30 秒)
lease-renewal-interval-in-seconds: 1
#Eureka服务端在收到最后一次心跳等待时间上限.单位为秒(默认90 秒),超时将剔除服务
lease-expiration-duration-in-seconds: 2
PaymentMain8001 .java
package com.george.springcloud;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
/**
* @author Yang Hao
* @date 2020/9/14
*/
@SpringBootApplication
@EnableEurekaClient
@EnableDiscoveryClient
public class PaymentMain8001 {
public static void main(String[] args) {
SpringApplication.run(PaymentMain8001.class, args);
}
}
PaymentController .java
package com.george.springcloud.controller;
import com.george.springcloud.entities.CommonResult;
import com.george.springcloud.entities.Payment;
import com.george.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* @author Yang Hao
* @description
* @date 2020-09-14 16:10
*/
@RestController
@Slf4j
public class PaymentController {
@Resource
private PaymentService paymentService;
@Value("${server.port}")
private String serverPort;
@Resource
private DiscoveryClient discoveryClient;
@PostMapping(value = "/payment/create")
public CommonResult create(@RequestBody Payment payment) {
int result = paymentService.create(payment);
log.info("-------------插入结果:[{}]", result);
if (result > 0) {
return new CommonResult(200, "插入数据库成功,端口号: " + serverPort, result);
} else {
return new CommonResult(444, "插入数据库失败", result);
}
}
@GetMapping(value = "/payment/get/{id}")
public CommonResult getPaymentById(@PathVariable("id") Long id) {
Payment payment = paymentService.getPaymentById(id);
log.info("-------------查询结果:[{}]", payment);
if (payment != null) {
return new CommonResult(200, "查询成功,端口号: " + serverPort, payment);
} else {
return new CommonResult(444, "没有对应记录,查询 ID: " + id, null);
}
}
@GetMapping(value = "/payment/discovery")
public Object getDiscovery() {
List<String> services = discoveryClient.getServices();
for (String service : services) {
log.info("----------element:" + service);
}
List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
for (ServiceInstance instance : instances) {
log.info("serviceId:[{}], 主机名称:[{}], 端口号:[{}], url地址:[{}]", instance.getServiceId(), instance.getHost(), instance.getPort(), instance.getUri());
}
return this.discoveryClient;
}
/**
* ribbon负载均衡 rule
*
* @return
*/
@GetMapping(value = "/payment/lb")
public String getPaymentLB() {
return serverPort;
}
/**
* feign超时测试
*
* @return
*/
@GetMapping("/payment/feign/timeout")
public String paymentFeignTimeOut() {
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
return serverPort;
}
/**
* P94用,sleuth+zipkin链路监控使用
*
* @return
*/
@GetMapping("/payment/zipkin")
public String paymentZipkin() {
return "hi,I am payment_zipkin server fall back, welcome to";
}
}
PaymentDao .java
package com.george.springcloud.dao;
import com.george.springcloud.entities.Payment;
import org.apache.ibatis.annotations.Mapper;
/**
* @author Yang Hao
* @description
* @date 2020-09-14 15:09
*/
@Mapper
public interface PaymentDao {
int create(Payment payment);
Payment getPaymentById(Long id);
}
PaymentService .java
package com.george.springcloud.service;
import com.george.springcloud.entities.Payment;
/**
* @author Yang Hao
* @description
* @date 2020-09-14 16:07
*/
public interface PaymentService {
int create(Payment payment);
Payment getPaymentById(Long id);
}
PaymentServiceImpl.java
package com.george.springcloud.service.impl;
import com.george.springcloud.dao.PaymentDao;
import com.george.springcloud.entities.Payment;
import com.george.springcloud.service.PaymentService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
/**
* @author Yang Hao
* @description
* @date 2020-09-14 16:07
*/
@Service
public class PaymentServiceImpl implements PaymentService {
@Resource
private PaymentDao paymentDao;
@Override
public int create(Payment payment) {
return paymentDao.create(payment);
}
@Override
public Payment getPaymentById(Long id) {
return paymentDao.getPaymentById(id);
}
}
PaymentMain8002
server:
port: 8002
spring:
application:
name: cloud-payment-service
datasource:
#当前数据源操作类型
type: com.alibaba.druid.pool.DruidDataSource
#mysql驱动包
driver-class-name: org.gjt.mm.mysql.Driver
url: jdbc:mysql://localhost:3306/cloud2020?useUnicode=true&characterEncoding=utf8&useSSL=false
username: root
password: 123456
mybatis:
mapperLocations: classpath:mapper/*.xml
#所有entity别名类所在包
type-aliases-package: com.george.springcloud.entities
eureka:
client:
#是否将自己注册到注册中心, 默认true
register-with-eureka: true
#是否从EurekaServer抓取已有的注册信息,单机无所谓,集群必须设置为true配合ribbon使用负载均衡
fetch-registry: true
service-url:
# defaultZone: http://localhost:7001/eureka #单机版
#集群版
defaultZone: http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka
instance:
instance-id: payment8002
#访问路径可以显示IP地址
prefer-ip-address: true
三、搭建订单中心
OrderMain80.java
package com.george.springcloud;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
/**
* @author Yang Hao
* @date 2020/9/14
*/
@SpringBootApplication
@EnableEurekaClient
//@RibbonClient(name = "CLOUD-PAYMENT-SERVICE", configuration = MyselfRule.class)
public class OrderMain80 {
public static void main(String[] args) {
SpringApplication.run(OrderMain80.class, args);
}
}
application.yml
server:
port: 9099
spring:
application:
name: cloud-order-service
# #P94 需要的配置
# zipkin:
# base-url: http://localhost:9411
# sleuth:
# sampler:
# probability: 1 #采样率值介于0-1之间,1标识全部采集
eureka:
client:
#是否将自己注册到注册中心, 默认true
register-with-eureka: true
#是否从EurekaServer抓取已有的注册信息,单机无所谓,集群必须设置为true配合ribbon使用负载均衡
fetch-registry: true
service-url:
# defaultZone: http://localhost:7001/eureka #单机版
defaultZone: http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka #集群版
ApplicationContextConfig.java
package com.george.springcloud.config;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
/**
* @author Yang Hao
* @description 消费者只关心微服务名称.
* @date 2020-09-14 16:54
*/
@Configuration
public class ApplicationContextConfig {
@Bean
@LoadBalanced //为了试验自己写的rule
//使用@LoadBalanced注解赋予RestTemplate负载均衡的能力
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
MyselfRule .java
package com.george.myrule;
import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.RandomRule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author Yang Hao
* @description Ribbon自定义IRule规则
* @date 2020-09-16 14:24
*/
@Configuration
public class MyselfRule {
@Bean
public IRule myRule() {
return new RandomRule();
}
}
package com.george.springcloud.controller;
import com.george.springcloud.entities.CommonResult;
import com.george.springcloud.entities.Payment;
import com.george.springcloud.lb.MyLoadBalancer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
import java.net.URI;
import java.util.List;
/**
* @author Yang Hao
* @description
* @date 2020-09-14 16:51
*/
@RestController
@Slf4j
public class OrderController {
// public static final String PAYMENT_URL = "http://localhost:8001";
//集群负载均衡
public static final String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVICE";
@Resource
private RestTemplate restTemplate;
@Resource
private MyLoadBalancer myLoadBalancer;
@Resource
private DiscoveryClient discoveryClient;
@PostMapping(value = "/consumer/payment/create")
public CommonResult<Payment> create(@RequestBody Payment payment) {
return restTemplate.postForObject(PAYMENT_URL + "/payment/create", payment, CommonResult.class);
}
@GetMapping("/consumer/payment/get/{id}")
public CommonResult<Payment> getPayment(@PathVariable("id") Long id) {
return restTemplate.getForObject(PAYMENT_URL + "/payment/get/" + id, CommonResult.class);
}
@GetMapping("/consumer/payment/getForEntity/{id}")
public CommonResult<Payment> getPaymentEntity(@PathVariable("id") Long id) {
ResponseEntity<CommonResult> entity = restTemplate.getForEntity(PAYMENT_URL + "/payment/get/" + id, CommonResult.class);
if (entity.getStatusCode().is2xxSuccessful()) {
return entity.getBody();
} else {
return new CommonResult<>(444, "操作失败");
}
}
@GetMapping(value = "/consumer/payment/lb")
public String getPaymentLB() {
List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
if (instances == null || instances.size() <= 0) {
return null;
}
ServiceInstance serviceInstance = myLoadBalancer.instances(instances);
URI uri = serviceInstance.getUri();
return restTemplate.getForObject(uri + "/payment/lb", String.class);
}
/**
* P94用,sleuth+zipkin链路监控使用
*
* @return
*/
@GetMapping("/consumer/payment/zipkin")
public String paymentZipkin() {
String result = restTemplate.getForObject("http://localhost:8001" + "/payment/zipkin/", String.class);
return result;
}
}