您的位置:首页 > 编程语言 > Java开发

Springcloud入门第二篇

2019-08-01 11:02 441 查看
版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。 本文链接:https://blog.csdn.net/qq_39992641/article/details/98034725

生产者消费者注册以及调用演示

基础的创建请看我的上一篇文章
再创建两个model order和user

order依赖

<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
<version>2.0.3.RELEASE</version>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<!-- 做负载均衡的 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
<version>2.0.3.RELEASE</version>
</dependency>

</dependencies>

order代码

启动类
@SpringBootApplication
@EnableEurekaClient
public class OrderApp {
public static void main(String[] args) {
SpringApplication.run(OrderApp.class,args);
}

/**
* 微服务在不同的服务之间调用走的是rest风格
* 可以用这个简化服务调用的过程
* @return
*/
@Bean
@LoadBalanced
RestTemplate restTemplate(){
return new RestTemplate();
}
}
.
controller
@RestController
public class OrderController {
@Autowired
OrderService orderService;

@RequestMapping("/order")
public String addOrder(String name,int id){
String result = orderService.getUser(id);
return "商品"+name+"生成订单:"+result;
}
}

service
@Service
public class OrderService {
@Autowired
RestTemplate restTemplate;
public String getUser(int id){

/**
* yidiankt-user  erueka里面服务的名字
*/
String url = "http://yidiankt-user/user/{id}";
/**
* 通过这个方法来调用其他的服务 获取信息
*/
String info = restTemplate.getForObject(url,String.class,id);
return info;
}

}

xml
server:
port: 8811
#  服务器注册到eureka的名称
spring:
application:
name: yidiankt-order
#  服务注册到eureka的地址
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:8888/eureka

user 代码

controller
package Userstater.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class userclinecontroller {
@RequestMapping("/user/{id}")
public String getUser(@PathVariable("id") int id){
if(id == 1){
return  "yidiankt";
}else if (id == 2){
return "张喜属猪";
}else {
return "张喜是猪";
}

}
}

启动类
@SpringBootApplication
//开启eureka的客户端注解
@EnableEurekaClient
public class UserApp {
public static void main(String[] args) {
SpringApplication.run(UserApp.class,args);
}
}

xml
server:
port: 8810
spring:
application:
name: yidiankt-user
#    服务注册到eureka地址
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:8888/eureka
#      因为该应用为注册中心
register-with-eureka: true
#    是否需要从rureka上获取注册信息
fetch-registry: true

即使是目前的三个项目启动后 eureka的 注册中心挂掉了 也同样能够 进行正常是使用 eureka会进入保护模式 不会踢掉任何一个服务

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: