当前位置: 首页 > news >正文

ios7 风格 网站大连市建设工程招标信息网

ios7 风格 网站,大连市建设工程招标信息网,wordpress目录关seo,网站前台功能我们将以一个简单的电商系统为例#xff0c;实现微服务架构#xff0c;逐步用Java代码详细实现每个模块#xff0c;并配合注释帮助小白理解。在这个实现中#xff0c;我们使用以下工具和框架#xff1a; Spring Boot#xff1a;用于构建微服务。Spring Cloud#xff1a…        我们将以一个简单的电商系统为例实现微服务架构逐步用Java代码详细实现每个模块并配合注释帮助小白理解。在这个实现中我们使用以下工具和框架 Spring Boot用于构建微服务。Spring Cloud用于服务注册、发现、负载均衡等。Docker用于容器化服务。Kubernetes (K8s)用于部署到生产环境。MySQL/MongoDB/PostgreSQL不同服务独立数据库。RabbitMQ用于消息队列。Prometheus Grafana用于监控。 以下是完整的实现步骤。 一、用户服务 (User Service)的实现 1. 环境搭建 1.1 必备工具安装 确保安装以下工具 Java 17MavenDockerKubernetes (minikube 或云上的K8s服务)RabbitMQ数据库MySQL/PostgreSQL/MongoDBIDEIntelliJ IDEA 或 VS Code 2. 功能 管理用户信息用户注册、查询。 2.1 数据库准备 我们使用 PostgreSQL 来存储用户数据。 创建数据库和表 CREATE DATABASE user_service; CREATE TABLE users (id SERIAL PRIMARY KEY,username VARCHAR(255) NOT NULL UNIQUE,email VARCHAR(255) NOT NULL UNIQUE,created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP );2.2 创建 Spring Boot 项目 生成项目Spring Initializr 依赖 Spring WebSpring Data JPAPostgreSQL Driver 2.3 实现用户服务 application.yml 配置文件 配置数据库连接 server:port: 8081 # 服务运行的端口号spring:datasource:url: jdbc:postgresql://localhost:5432/user_serviceusername: postgres # 数据库用户名password: password # 数据库密码jpa:hibernate:ddl-auto: update # 自动更新数据库结构show-sql: true # 显示 SQL 查询日志User 实体类 package com.example.userservice.model;import jakarta.persistence.*; import java.time.LocalDateTime;/*** 用户实体类对应数据库表 users。*/ Entity Table(name users) public class User {IdGeneratedValue(strategy GenerationType.IDENTITY)private Long id; // 用户唯一 IDColumn(nullable false, unique true)private String username; // 用户名唯一Column(nullable false, unique true)private String email; // 用户邮箱唯一Column(name created_at, updatable false)private LocalDateTime createdAt LocalDateTime.now(); // 用户注册时间// Getters 和 Setters用于封装字段访问public Long getId() {return id;}public void setId(Long id) {this.id id;}public String getUsername() {return username;}public void setUsername(String username) {this.username username;}public String getEmail() {return email;}public void setEmail(String email) {this.email email;}public LocalDateTime getCreatedAt() {return createdAt;}public void setCreatedAt(LocalDateTime createdAt) {this.createdAt createdAt;} }UserRepository 接口 package com.example.userservice.repository;import com.example.userservice.model.User; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository;/*** 用户数据访问接口提供 CRUD 操作。*/ Repository public interface UserRepository extends JpaRepositoryUser, Long {User findByUsername(String username); // 根据用户名查询用户 }UserService 服务层 package com.example.userservice.service;import com.example.userservice.model.User; import com.example.userservice.repository.UserRepository; import org.springframework.stereotype.Service;import java.util.Optional;/*** 用户服务类包含业务逻辑。*/ Service public class UserService {private final UserRepository userRepository;public UserService(UserRepository userRepository) {this.userRepository userRepository;}/*** 注册新用户。* * param user 包含用户名和邮箱的用户对象* return 保存后的用户对象包含生成的 ID 和注册时间*/public User registerUser(User user) {return userRepository.save(user); // 保存到数据库}/*** 根据用户名查找用户。* * param username 要查询的用户名* return 包含用户对象的 Optional如果未找到则为空*/public OptionalUser findUserByUsername(String username) {return Optional.ofNullable(userRepository.findByUsername(username));} }UserController 控制器 package com.example.userservice.controller;import com.example.userservice.model.User; import com.example.userservice.service.UserService; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*;import java.util.Optional;/*** 用户服务的 REST 控制器。*/ RestController RequestMapping(/api/users) public class UserController {private final UserService userService;public UserController(UserService userService) {this.userService userService;}/*** 注册新用户的 API。* * param user 从请求体接收的用户对象* return 返回注册成功的用户*/PostMappingpublic ResponseEntityUser registerUser(RequestBody User user) {return ResponseEntity.ok(userService.registerUser(user));}/*** 根据用户名查找用户的 API。* * param username 请求路径中的用户名* return 返回找到的用户或 404*/GetMapping(/{username})public ResponseEntityUser findUserByUsername(PathVariable String username) {OptionalUser user userService.findUserByUsername(username);return user.map(ResponseEntity::ok).orElse(ResponseEntity.notFound().build());} }2.4 测试用户服务 启动服务后 注册用户 curl -X POST -H Content-Type: application/json \ -d {username: haha_jam, email: hahaexample.com} \ http://localhost:8081/api/users响应 {id: 1,username: haha_jam,email: hahaexample.com,createdAt: 2024-12-20T10:00:00 }查询用户 curl http://localhost:8081/api/users/haha_jam响应 {id: 1,username: haha_jam,email: hahaexample.com,createdAt: 2024-12-20T10:00:00 }3. 服务注册与发现 在完整微服务中我们使用 Spring Cloud Eureka 来实现服务注册和发现。 3.1 什么是服务注册与发现 在微服务架构中服务是分布式的每个服务都可能运行在不同的主机或容器中。为了让服务之间能够互相通信需要一种机制来找到其他服务的地址和端口。 服务注册与发现原理 Eureka Server服务注册中心用来维护所有服务的地址列表。每个服务如用户服务、订单服务都会向 Eureka Server 注册自己。Eureka Client微服务实例本身会向 Eureka Server 注册并定期发送心跳来告诉注册中心它是健康的。服务发现当一个服务需要调用另一个服务时它会向 Eureka Server 查询目标服务的地址列表。 配置步骤包括 创建 Eureka Server。将用户服务注册到 Eureka。添加 API 网关。 3.2 创建 Eureka Server Eureka Server 是服务注册中心所有服务都会向它注册。 3.2.1 生成 Eureka Server 项目 打开 Spring Initializr。 配置项目 Project: MavenLanguage: JavaSpring Boot: 3.0.0Dependencies: Spring Cloud Eureka Server 下载生成的项目并解压。 3.2.2 配置 Eureka Server 1. 添加依赖 在 pom.xml 中确认以下依赖已经存在 dependencygroupIdorg.springframework.cloud/groupIdartifactIdspring-cloud-starter-netflix-eureka-server/artifactId /dependency2. 配置 application.yml 在 src/main/resources/application.yml 中配置 Eureka Server server:port: 8761 # Eureka Server 的默认端口spring:application:name: eureka-server # 应用名称eureka:client:register-with-eureka: false # Eureka Server 本身不需要向其他注册中心注册fetch-registry: false # Eureka Server 不需要获取注册信息server:enable-self-preservation: false # 关闭自我保护模式测试环境可以关闭生产环境建议打开3. 启动类 在 src/main/java/com/example/eurekaserver/EurekaServerApplication.java 文件中添加 EnableEurekaServer 注解。 package com.example.eurekaserver;import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;/*** Eureka Server Application - 服务注册中心*/ SpringBootApplication EnableEurekaServer // 启用 Eureka Server 功能 public class EurekaServerApplication {public static void main(String[] args) {SpringApplication.run(EurekaServerApplication.class, args);} }3.2.3 启动 Eureka Server 使用 IDE 或命令行运行 EurekaServerApplication。打开浏览器访问http://localhost:8761 你会看到 Eureka Server 的管理页面显示 No instances available。 3.3 将用户服务注册到 Eureka 现在我们需要将前面实现的 用户服务User Service 注册到 Eureka Server。 3.3.1 添加依赖 在用户服务的 pom.xml 中添加 Eureka Client 依赖 dependencygroupIdorg.springframework.cloud/groupIdartifactIdspring-cloud-starter-netflix-eureka-client/artifactId /dependency3.3.2 配置 application.yml 在 src/main/resources/application.yml 中添加 Eureka Client 配置 server:port: 8081 # 用户服务运行的端口spring:application:name: user-service # 服务名称Eureka 注册时的标识eureka:client:service-url:defaultZone: http://localhost:8761/eureka/ # Eureka Server 的地址3.3.3 修改启动类 在用户服务的启动类中添加 EnableEurekaClient 注解 package com.example.userservice;import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.EnableEurekaClient;/*** User Service Application - 用户服务*/ SpringBootApplication EnableEurekaClient // 启用 Eureka Client 功能 public class UserServiceApplication {public static void main(String[] args) {SpringApplication.run(UserServiceApplication.class, args);} }3.3.4 验证注册 启动 Eureka Server。启动 用户服务。在浏览器访问http://localhost:8761 你会看到 user-service 出现在 Instances currently registered with Eureka 列表中。 3.4 添加 API 网关 API 网关用于转发客户端请求到具体的微服务并支持负载均衡。 3.4.1 创建 API 网关项目 打开 Spring Initializr。配置项目 Project: MavenLanguage: JavaSpring Boot: 3.0.0Dependencies: Spring Cloud GatewaySpring Cloud Eureka Discovery 3.4.2 配置 API 网关 1. 添加依赖 在 pom.xml 中确认以下依赖 dependencygroupIdorg.springframework.cloud/groupIdartifactIdspring-cloud-starter-gateway/artifactId /dependency dependencygroupIdorg.springframework.cloud/groupIdartifactIdspring-cloud-starter-netflix-eureka-client/artifactId /dependency2. 配置 application.yml 在 src/main/resources/application.yml 中配置网关 server:port: 8080 # API 网关运行的端口spring:application:name: api-gateway # 应用名称cloud:gateway:routes:- id: user-service # 路由 IDuri: lb://user-service # 用户服务通过 Eureka 注册的服务名predicates:- Path/api/users/** # 匹配以 /api/users 开头的请求eureka:client:service-url:defaultZone: http://localhost:8761/eureka/ # Eureka Server 地址3. 启动类 在 src/main/java/com/example/apigateway/ApiGatewayApplication.java 文件中添加 EnableEurekaClient 注解。 package com.example.apigateway;import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.EnableEurekaClient;/*** API Gateway Application - 网关服务*/ SpringBootApplication EnableEurekaClient // 启用 Eureka Client 功能 public class ApiGatewayApplication {public static void main(String[] args) {SpringApplication.run(ApiGatewayApplication.class, args);} }3.4.3 验证 API 网关 启动 Eureka Server。启动 用户服务。启动 API 网关。测试 API curl http://localhost:8080/api/users/john_doeAPI 网关会将请求转发到用户服务返回用户数据。 4. 部署到K8S 4.1 容器化服务 (Docker) 在项目根目录下创建 Dockerfile FROM openjdk:17-jdk-slim COPY target/user-service-0.0.1-SNAPSHOT.jar user-service.jar ENTRYPOINT [java, -jar, /user-service.jar]4.2 构建Docker镜像 打包项目 mvn clean package -DskipTests构建镜像 docker build -t user-service:1.0 .运行容器 docker run -d -p 8081:8081 user-service:1.0 4.3 部署到 Kubernetes 创建 user-service-deployment.yml apiVersion: apps/v1 kind: Deployment metadata:name: user-service spec:replicas: 3selector:matchLabels:app: user-servicetemplate:metadata:labels:app: user-servicespec:containers:- name: user-serviceimage: user-service:1.0ports:- containerPort: 8081 --- apiVersion: v1 kind: Service metadata:name: user-service spec:selector:app: user-serviceports:- protocol: TCPport: 80targetPort: 8081type: LoadBalancer4.4 部署到 K8s 集群 应用配置 kubectl apply -f user-service-deployment.yml查看服务 kubectl get services 二、产品服务 (Product Service) 和订单服务 (Order Service)的实现 每个服务有自己的数据库提供REST API并实现服务注册和发现确保服务之间的解耦和可扩展性。 1. 产品服务 (Product Service) 功能管理商品信息包括商品的添加、修改和查询。 1.1 数据库准备 我们使用 MongoDB 来存储商品数据。 创建数据库和集合 use product_service; db.createCollection(products);1.2 创建 Spring Boot 项目 生成项目Spring Initializr 依赖 Spring WebSpring Data MongoDB 1.3 实现产品服务 application.yml 配置文件 配置MongoDB连接 server:port: 8082spring:data:mongodb:uri: mongodb://localhost:27017/product_serviceProduct 实体类 package com.example.productservice.model;import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document;/*** 在MongoDB中表示产品文档的产品实体类。*/ Document(collection products) public class Product {Idprivate String id; // 商品ID由MongoDB生成private String name; // 商品名称private String description; // 商品描述private double price; // 商品价格private int stock; // 商品库存// Getters and Setterspublic String getId() {return id;}public void setId(String id) {this.id id;}public String getName() {return name;}public void setName(String name) {this.name name;}public String getDescription() {return description;}public void setDescription(String description) {this.description description;}public double getPrice() {return price;}public void setPrice(double price) {this.price price;}public int getStock() {return stock;}public void setStock(int stock) {this.stock stock;} }ProductRepository 接口 package com.example.productservice.repository;import com.example.productservice.model.Product; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.stereotype.Repository;/*** 用于在Product实体上执行CRUD操作的存储库接口。*/ Repository public interface ProductRepository extends MongoRepositoryProduct, String {Product findByName(String name); // 根据商品名称查询商品 }ProductService 服务层 package com.example.productservice.service;import com.example.productservice.model.Product; import com.example.productservice.repository.ProductRepository; import org.springframework.stereotype.Service;import java.util.Optional;/*** 管理产品的服务类。包含产品相关操作的业务逻辑。*/ Service public class ProductService {private final ProductRepository productRepository;public ProductService(ProductRepository productRepository) {this.productRepository productRepository;}/*** 添加新产品。* * param product 包含产品详细信息的产品对象。* return Saved 带生成ID的产品对象*/public Product addProduct(Product product) {return productRepository.save(product);}/*** 按名称查找产品。* * param name 产品名称。* return 含有找到的产品如果没有找到则为空。*/public OptionalProduct findProductByName(String name) {return Optional.ofNullable(productRepository.findByName(name));}/*** 按指定数量减少库存。* * param productId 产品ID。* param quantity 数量减少。* return 更新了Product对象。*/public Product decreaseStock(String productId, int quantity) {Product product productRepository.findById(productId).orElseThrow(() - new RuntimeException(Product not found));if (product.getStock() quantity) {product.setStock(product.getStock() - quantity);return productRepository.save(product);} else {throw new RuntimeException(Insufficient stock);}} }ProductController 控制器 package com.example.productservice.controller;import com.example.productservice.model.Product; import com.example.productservice.service.ProductService; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*;/*** 与产品相关的端点的REST控制器。*/ RestController RequestMapping(/api/products) public class ProductController {private final ProductService productService;public ProductController(ProductService productService) {this.productService productService;}/*** 添加新产品的端点。* * param product 请求体中的产品对象。* return 包含已保存产品的responseentity。*/PostMappingpublic ResponseEntityProduct addProduct(RequestBody Product product) {return ResponseEntity.ok(productService.addProduct(product));}/*** 根据名称查找产品的端点。* * param name 产品名称作为路径变量传递。* return 包含产品如果找到。*/GetMapping(/{name})public ResponseEntityProduct findProductByName(PathVariable String name) {return productService.findProductByName(name).map(ResponseEntity::ok).orElse(ResponseEntity.notFound().build());}/*** 减少产品库存的终点。* * param productId 产品ID。* param quantity 数量减少。* return 包含更新后的产品。*/PutMapping(/{productId}/decrease-stock/{quantity})public ResponseEntityProduct decreaseStock(PathVariable String productId, PathVariable int quantity) {return ResponseEntity.ok(productService.decreaseStock(productId, quantity));} }1.4 测试产品服务 启动服务后 添加商品 curl -X POST -H Content-Type: application/json \ -d {name: Laptop, description: High-performance laptop, price: 1000, stock: 50} \ http://localhost:8082/api/products响应 {id: 605c72ef1532072a20b0f119,name: Laptop,description: High-performance laptop,price: 1000,stock: 50 }查询商品 curl http://localhost:8082/api/products/Laptop响应 {id: 605c72ef1532072a20b0f119,name: Laptop,description: High-performance laptop,price: 1000,stock: 50 }2. 订单服务 (Order Service) 功能管理用户的订单包括创建订单、查询订单、更新订单状态等。 2.1 数据库准备 我们使用 MySQL 来存储订单数据。 创建数据库和表 CREATE DATABASE order_service; CREATE TABLE orders (id INT AUTO_INCREMENT PRIMARY KEY,user_id INT NOT NULL,product_id VARCHAR(255) NOT NULL,quantity INT NOT NULL,total_price DOUBLE NOT NULL,order_status VARCHAR(255) DEFAULT PENDING,created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP );2.2 创建 Spring Boot 项目 生成项目Spring Initializr 依赖 Spring WebSpring Data JPAMySQL Driver 2.3 实现订单服务 application.yml 配置文件 配置MySQL连接 server:port: 8083spring:datasource:url: jdbc:mysql://localhost:3306/order_serviceusername: rootpassword: rootjpa:hibernate:ddl-auto: updateshow-sql: trueOrder 实体类 package com.example.orderservice.model;import jakarta.persistence.*; import java.time.LocalDateTime;/*** 表示数据库中的订单表的订单实体类。*/ Entity Table(name orders) public class Order {IdGeneratedValue(strategy GenerationType.IDENTITY)private Long id;Column(nullable false)private Long userId; // 用户IDColumn(nullable false)private String productId; // 商品IDColumn(nullable false)private int quantity; // 购买数量Column(nullable false)private double totalPrice; // 总金额Column(name order_status, nullable false)private String orderStatus PENDING; // 订单状态Column(name created_at, updatable false )private LocalDateTime createdAt LocalDateTime.now(); // 订单创建时间// Getters and Setters }OrderRepository 接口 package com.example.orderservice.repository;import com.example.orderservice.model.Order; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository;/*** 用于在Order实体上执行CRUD操作的存储库接口。*/ Repository public interface OrderRepository extends JpaRepositoryOrder, Long {Order findByUserIdAndOrderStatus(Long userId, String orderStatus); // 根据用户ID和订单状态查询订单 }OrderService 服务层 package com.example.orderservice.service;import com.example.orderservice.model.Order; import com.example.orderservice.repository.OrderRepository; import org.springframework.stereotype.Service;import java.util.Optional;/*** 用于管理订单的服务类。包含订单相关操作的业务逻辑。*/ Service public class OrderService {private final OrderRepository orderRepository;public OrderService(OrderRepository orderRepository) {this.orderRepository orderRepository;}/*** 创建一个新订单。* * param order 包含订单详细信息的订单对象。* return 保存订单对象。*/public Order createOrder(Order order) {return orderRepository.save(order);}/*** 通过用户ID和状态查找订单。* * param userId 用户ID。* param orderStatus 订单状态例如‘PENDING’。* return 可选包含找到的订单如果没有找到则为空。*/public OptionalOrder findOrderByUserIdAndStatus(Long userId, String orderStatus) {return Optional.ofNullable(orderRepository.findByUserIdAndOrderStatus(userId, orderStatus));} }OrderController 控制器 package com.example.orderservice.controller;import com.example.orderservice.model.Order; import com.example.orderservice.service.OrderService; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*;/*** 与订单相关的端点的REST控制器。*/ RestController RequestMapping(/api/orders) public class OrderController {private final OrderService orderService;public OrderController(OrderService orderService) {this.orderService orderService;}/*** 创建新订单的端点。* * param order 从请求体中订购对象。* return ResponseEntity包含保存的订单。*/PostMappingpublic ResponseEntityOrder createOrder(RequestBody Order order) {return ResponseEntity.ok(orderService.createOrder(order));}/*** 根据用户ID和状态查找订单的端点。* * param userId 用户ID。* param orderStatus 订单状态作为路径变量传递。* return ResponseEntity包含找到的订单如果存在。*/GetMapping(/{userId}/{orderStatus})public ResponseEntityOrder findOrderByUserIdAndStatus(PathVariable Long userId, PathVariable String orderStatus) {return orderService.findOrderByUserIdAndStatus(userId, orderStatus).map(ResponseEntity::ok).orElse(ResponseEntity.notFound().build());} }总结 在这个扩展中我们设计了三个服务用户服务产品服务和订单服务。每个服务具有自己的数据库提供REST API能够完成各自的功能如商品管理、订单创建与查询。服务之间通过HTTP协议相互通信服务之间通过微服务架构进行解耦确保系统可扩展和维护。
http://www.eeditor.cn/news/123366/

相关文章:

  • 咸阳网站开发公司地址汽车网站建设模板
  • 佛山市网站建设分站企业北京企业建站模板
  • 站长统计app软件下载官网做网站的接口是意思
  • 做h5哪些网站好 知乎卫浴网站模板
  • 乐清建设公司网站网站推广优化外包公司
  • wap电影网站建设天河建设网站专家
  • 做网站花都区手机app下载软件安装
  • 网站个性化制作网站建设选哪家公司好
  • 网站集约化建设国内网络营销公司排名
  • 江西省赣州市地图广告优化师工资一般多少
  • 国内摄影作品网站如何自助建网站
  • php网站开发用什么php海口建站网站模板
  • 中国住建部网站查询网柒比贰主题wordpress
  • 用手机域名做网站有多少做电影网站多少带宽
  • 做个外贸网站设计网站开发历史
  • 博罗企业网站建设搬瓦工vps wordpress
  • 行业网站开发专业网站建设包括哪些
  • 手机网站分辨率做多大wordpress主题 免
  • 长沙手机网站建设公司排名在线网站建设培训班
  • 电子商务网站建设的平台四川省建设厅网站川北医学院
  • 浙江新华建设有限公司网站济南建设网站需要
  • 如何给网站写文章asp.net 网站管理系统
  • 高明网站开发杭州网络公司建网站
  • 做网站的怎么学新手如何建站
  • 网站建设男装定位邢台学校网站建设费用
  • 南京做网站南京乐识专业广告协会网站建设方案
  • 萍乡网站建设wordpress多语言内容添加
  • 三明北京网站建设WordPress主题怎么保存
  • 网站建设 管理 会议纪要求个没封的w站2021你懂
  • metro网站模板医疗机构网站以患者做宣传