说明
我们上一篇已经演示了在Eureka集群下单个服务提供微服务的案例,我们这篇就演示多个服务提供的案例。我们复制cloud-provider-payment8001,并命名新的项目为cloud-provider-payment8002。
在父Pom中添加对应的module
<modules>
<module>cloud-provider-payment8001</module>
<module>cloud-provider-payment8002</module>
<module>cloud-consumer-order8080</module>
<module>cloud-api-commons</module>
<module>cloud-eureka-server7001</module>
<module>cloud-eureka-server7002</module>
<module>cloud-eureka-server7003</module>
</modules>
更改复制来的pom的artifactId
<artifactId>cloud-provider-payment8002</artifactId>
更改复制来的yml
server:
port: 8002
eureka:
client:
#表示是否将自己注册进Eurekaserver默认为true。
register-with-eureka: true
#是否从EurekaServer抓取已有的注册信息,默认为true。单节点无所谓,集群必须设置为true才能配合ribbon使用负载均衡
fetchRegistry: true
service-url:
defaultZone: http://127.0.0.1:7001/eureka,http://localhost:7002/eureka,http://192.168.0.135:7003/eureka
spring:
application:
name: cloud-payment-service
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: org.gjt.mm.mysql.Driver
url: jdbc:mysql://localhost:3306/my?useUnicode=true&characterEncoding=utf-8&useSSL=false
username: root
password: 123456
mybatis:
mapper-locations: classpath:mapper/*.xml
type-aliases-package: com.gcl.springcloud.entities
更改复制来的启动类
package com.gcl.springcloud;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@EnableEurekaClient
@SpringBootApplication
public class PaymentMain8002 {
public static void main(String[] args) {
SpringApplication.run( PaymentMain8002.class , args );
}
}
改控制层(为了区分是那个微服务提供的服务,两个项目的控制层代码一样,用端口区分)
package com.gcl.springcloud.controller;
import com.gcl.springcloud.entities.CommonResult;
import com.gcl.springcloud.entities.Payment;
import com.gcl.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
@RestController
@Slf4j
public class PaymentController {
@Value("${server.port}")
private String serverPort;//添加serverPort
@Resource
private PaymentService paymentService;
@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 , "插入数据失败,端口为: "+serverPort );
}
}
@GetMapping( value = "/payment/get/{id}")
public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id ){
Payment payment = paymentService.getPaymentById(id);
if ( payment != null ){
return new CommonResult( 200, "查询成功,端口为: "+serverPort, payment );
}else {
return new CommonResult( 444, ",端口为: "+serverPort+" ,没有ID为:"+ id+ " 对应的记录,查询失败");
}
}
}
运行