关于后端:Eureka使用模板

9次阅读

共计 2380 个字符,预计需要花费 6 分钟才能阅读完成。

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);
    }

}
正文完
 0