当前位置: 首页 > 后端技术 > Java

Eureka使用模板

时间:2023-04-01 17:22:23 Java

Eureka本身是一个springboot项目,所以至少需要3个springboot项目(Eureka、服务提供者、服务消费者)。本文主要提供Eureka配置信息和简单的远程调用配置信息1Eureka配置1.引入pom依赖org.springframework.cloudspring-cloud-starter-netflix-eureka-server2.配置文件server:port:10086#端口号spring:application:name:cloud-eureka#servicename#eureka地址信息eureka:client:service-url:defaultZone:http://127.0.0.1:10086/eureka/eureka本身也要在eureka中注册3.在springBoot启动类中添加注解添加注解@EnableEurekaServer2消费者配置1、引入pom依赖org.springframework.cloudspring-cloud-starter-netflix-eureka-client依赖跟eureka不一样!!!2.配置文件服务器:端口:8081#端口号#springspring:application:name:cloud-payment-provider#servicenamedatasource:type:com.alibaba.druid.pool.DruidDataSourcedriver-class-name:org.gjt.mm.mysql.Driverurl:jdbc:mysql://localhost:3306/base-cloud?autoReconnect=true&useUnicode=true&character_set_server=utf8mb4&zeroDateTimeBehavior=convertToNull&useSSL=false用户名:root密码:123456#eureka地址信息eureka:client:service-url:defaultZone:http://127.0.0.1:10086/eureka/**主要是spring和eureka配置的端口号和服务名**3.在springBoot启动类中添加注解添加注解@EnableEurekaClient提供者配置与消费者配置相同。本质上,提供者和消费者对于尤里卡来说是一样的。它们都是来自客户端的远程调用。使用RestTemplate调用简单模板.RestTemplate;@ConfigurationpublicclassRestTemplateConfig{@Bean@LoadBalanced//负载均衡publicRestTemplategetRestTemplate(){returnnewRestTemplate();}}然后在你想使用的地方注入它。使用线路地址为http://服务名称/路由示例importcom.ray.entity.CmmonsResult;importcom.ray.entity.Payment;导入org.springframework.beans.factory.annotation.Autowired;导入org.springframework.web.bind.annotation.*;导入org.springframework.web.client.RestTemplate;@RestController@RequestMapping("/consumer")publicclassTestController{//http://服务名publicstaticfinalStringPAYMENT_URL="http://cloud-payment-provider";@AutowiredprivateRestTemplaterestTemplate;//@PostMapping("/payment/create")publicCMmonsResultcreate(@RequestBodyPaymentpayment){returnrestTemplate.postForObject(PAYMENT_URL+"/payment/save",payment,CMmonsResult.class);}//@GetMapping("/payment/get/{id}")publicCMmonsResultgetPayment(@PathVariable("id")Longid){returnrestTemplate.getForObject(PAYMENT_URL+"/payment/get/"+id,CmmonsResult.class);}}