Eureka本身是一个springboot项目,所以需要最少3个springBoot项目(Eureka,服务提供者,服务消费者),本文主要为Eureka的配置信息以及简易的远程调用
配置信息
1Eureka配置
1、引入pom依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
2、配置文件
server:
port: 10086 #端口号
spring:
application:
name: cloud-eureka #服务名
#eureka地址信息
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:10086/eureka/
eureka本身也要注册在eureka中
3、增加注解
在springBoot启动类上增加注解 @EnableEurekaServer
2消费者配置
1、引入pom依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
依赖与eureka的不一样!!!
2、配置文件
server:
port: 8081 #端口号
#spring
spring:
application:
name: cloud-payment-provider #服务名
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: org.gjt.mm.mysql.Driver
url: jdbc:mysql://localhost:3306/base-cloud?autoReconnect=true&useUnicode=true&character_set_server=utf8mb4&zeroDateTimeBehavior=convertToNull&useSSL=false
username: root
password: 123456
#eureka地址信息
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:10086/eureka/
**主要的是spring的端口号和服务名以及eureka配置
**
3、增加注解
springBoot启动类上增加注解 @EnableEurekaClient
提供者配置与消费者配置相同,本质上提供者和消费者对于eureka来说都一样,都是客户端
远程调用
使用 RestTemplate调用
简易模板
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;
@Configuration
public class RestTemplateConfig {
@Bean
@LoadBalanced //负载均衡
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
}
然后在要使用的地方进行注入使用就行 地址为http://服务名/路由
样例
import com.ray.entity.CmmonsResult;
import com.ray.entity.Payment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
@RestController
@RequestMapping("/consumer")
public class TestController {
//http://服务名
public static final String PAYMENT_URL = "http://cloud-payment-provider";
@Autowired
private RestTemplate restTemplate;
//
@PostMapping("/payment/create")
public CmmonsResult<Payment> create(@RequestBody Payment payment) {
return restTemplate.postForObject(PAYMENT_URL + "/payment/save", payment, CmmonsResult.class);
}
//
@GetMapping("/payment/get/{id}")
public CmmonsResult<Payment> getPayment(@PathVariable("id") Long id) {
return restTemplate.getForObject(PAYMENT_URL + "/payment/get/" + id, CmmonsResult.class);
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。