微服务架构, 简单的说就是将单体应用进一步拆分,拆分成更小的服务,每个服务都是一个可以独
立运行的项目。
一旦采用微服务系统架构,就势必会遇到这样几个问题:
对于上面的问题,是任何一个微服务设计者都不能绕过去的,因此大部分的微服务产品都针对每一
个问题提供了相应的组件来解决它们。
springcloud:
Spring Cloud是一系列框架的集合。它利用Spring Boot的开发便利性巧妙地简化了分布式系统基
础设施的开发,如服务发现注册、配置中心、消息总线、负载均衡、断路器、数据监控等,都可以用
Spring Boot的开发风格做到一键启动和部署。
Spring Cloud并没有重复制造轮子,它只是将目前各家公司开发的比较成熟、经得起实际考验的服
务框架组合起来,通过Spring Boot风格进行再封装屏蔽掉了复杂的配置和实现原理,最终给开发者留
出了一套简单易懂、易部署和易维护的分布式系统开发工具包。
父项pom.xml:
4.0.0 com.xujie springcloud_sp pom 1.0-SNAPSHOT shop_common shop_user shop_product shop_order 1.8 UTF-8 UTF-8 2.3.2.RELEASE Hoxton.SR9 2.2.6.RELEASE org.springframework.boot spring-boot-dependencies ${spring-boot.version} pom import
common公共模块:
所有的项目需要的依赖:
springcloud_sp com.xujie 1.0-SNAPSHOT 4.0.0 shop_common org.projectlombok lombok com.alibaba fastjson 1.2.56 mysql mysql-connector-java 5.1.6 org.springframework.boot spring-boot-starter-test org.springframework.boot spring-boot-starter-web 8 8
子项目:
4.0.0 com.xujie 0.0.1-SNAPSHOT springcloud_sp com.xujie 1.0-SNAPSHOT shop_product com.xujie shop_common 1.0-SNAPSHOT org.springframework.boot spring-boot-maven-plugin
调用其他模块:
package com.xujie.shop_order;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;@SpringBootApplication
public class ShopOrderApplication {public static void main(String[] args) {SpringApplication.run(ShopOrderApplication.class, args);}@Beanpublic RestTemplate restTemplate(){return new RestTemplate();}
}
controller:
package com.xujie.shop_order.controller;import com.xujie.common.model.Order;
import com.xujie.common.model.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;/*** @author 许缘* @company xxx公司* @create 2022-12-06 17:25*/
@RestController
@RequestMapping("/order")
public class ordercontroller {@Autowiredprivate RestTemplate restTemplate;@RequestMapping("/test/{pid}")public Order createOrder(@PathVariable("pid") Integer pid){Product product =restTemplate.getForObject("http://localhost:8080/product/getOne/"+pid,Product.class);//创建订单Order order = new Order();order.setOid(System.currentTimeMillis());order.setUid(12);order.setUsername("张三");order.setPid(product.getPid());order.setPname(product.getPname());order.setPprice(product.getPprice());order.setNumber(product.getStock());return order;}
}
效果图:
