Spring Cloud【Finchley】实战-01注册中心及商品微服务(下)

简介: Spring Cloud【Finchley】实战-01注册中心及商品微服务(下)

实体类 ProductCategory


过程同上,这里不赘述了 ,代码如下

domain实体类

package com.artisan.product.domain;
import lombok.Data;
import javax.persistence.*;
import java.util.Date;
@Data
@Table(name = "product_category")
@Entity
public class ProductCategory {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private String categoryId;
    private String categoryName;
    private Integer categoryType;
    private Date createTime;
    private Date updateTime;
}


Dao接口

package com.artisan.product.repository;
import com.artisan.product.domain.ProductCategory;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface ProductCategoryRepository extends JpaRepository<ProductCategory, String> {
    List<ProductCategory> findByCategoryTypeIn(List<Integer> categoryTypeList);
}

单元测试

package com.artisan.product.repository;
import com.artisan.product.domain.ProductCategory;
import com.netflix.discovery.converters.Auto;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.*;
@RunWith(SpringRunner.class)
@SpringBootTest
public class ProductCategoryRepositoryTest {
    @Autowired
    private ProductCategoryRepository productCategoryRepository;
    @Test
    public void findByCategoryTypeIn() {
        List<ProductCategory> list = productCategoryRepository.findByCategoryTypeIn(Arrays.asList(99, 98, 97));
        Assert.assertEquals(3,list.size());
    }
}


20190322233339862.png

Service层

ProductService 接口

package com.artisan.product.service;
import com.artisan.product.domain.Product;
import java.util.List;
public interface ProductService {
    // 查询上架商品
    List<Product>   getAllUpProduct();
}


ProductService 接口实现类

package com.artisan.product.service.impl;
import com.artisan.product.domain.Product;
import com.artisan.product.enums.ProductStatusEnum;
import com.artisan.product.repository.ProductRepository;
import com.artisan.product.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class ProductServiceImpl implements ProductService {
    @Autowired
    private ProductRepository productRepository;
    @Override
    public List<Product> getAllUpProduct() {
        return productRepository.findByProductStatus(ProductStatusEnum.UP.getCode());
    }
}



ProductStatusEnum

为了方便,将状态封装到了Enum中

package com.artisan.product.enums;
import lombok.Getter;
@Getter
public enum ProductStatusEnum {
    UP(0,"上架"),
    DOWN(1,"下架");
    private int code ;
    private String msg;
    ProductStatusEnum(int code, String msg){
        this.code = code;
        this.msg = msg;
    }
}


对接口进行单元测试

package com.artisan.product.service;
import com.artisan.product.ArtisanProductApplicationTests;
import com.artisan.product.domain.Product;
import com.artisan.product.enums.ProductStatusEnum;
import com.artisan.product.repository.ProductRepository;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;
import static org.junit.Assert.*;
@Component
public class ProductServiceTest extends ArtisanProductApplicationTests {
    @Autowired
    private ProductRepository productRepository;
    @Test
    public void getAllUpProduct() {
        List<Product> list =  productRepository.findByProductStatus(ProductStatusEnum.UP.getCode());
        Assert.assertEquals(3,list.size());
    }
}

20190323001136956.png

ProductCategoryService 接口

package com.artisan.product.service;
import com.artisan.product.domain.ProductCategory;
import java.util.List;
public interface ProductCategoryService {
    List<ProductCategory> findByCategoryTypeIn(List<Integer> categoryTypeList);
}


ProductCategoryService 接口实现类

package com.artisan.product.service.impl;
import com.artisan.product.domain.ProductCategory;
import com.artisan.product.repository.ProductCategoryRepository;
import com.artisan.product.service.ProductCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class ProductCategoryServiceImpl implements ProductCategoryService {
    @Autowired
    private ProductCategoryRepository productCategoryRepository;
    @Override
    public List<ProductCategory> findByCategoryTypeIn(List<Integer> categoryTypeList) {
        return productCategoryRepository.findByCategoryTypeIn(categoryTypeList);
    }
}


单元测试

package com.artisan.product.service.impl;
import com.artisan.product.ArtisanProductApplicationTests;
import com.artisan.product.domain.ProductCategory;
import com.artisan.product.repository.ProductCategoryRepository;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.*;
@Component
public class ProductCategoryServiceImplTest extends ArtisanProductApplicationTests {
    @Autowired
    private ProductCategoryRepository productCategoryRepository;
    @Test
    public void findByCategoryTypeIn() {
       List<ProductCategory> list =  productCategoryRepository.findByCategoryTypeIn(Arrays.asList(99,98,97));
        Assert.assertEquals(3,list.size());
    }
}


20190323002005842.png


Controller层


20190322222722642.png


先来观察下,返回给前端的数据

code , msg , 泛型的data 是最外层的数据,那封装下吧 。 可以理解为也是一个VO(View Object)对象,包含3个节点(code msg 泛型的data)

同时data节点 [] ,自然是个数组了,可包含多个{}对象。

20190323005532294.png


按照上图的划分,也把这些信息封装成VO吧。

为了避免引起误解,我们把

20190323010610710.png

改为products .


VO封装

ResultVO 前后台交互的统一格式模板

package com.artisan.product.vo;
import lombok.Getter;
@Getter
public class Result<T> {
    private Integer code ;
    private String msg ;
    private T data;
    /**
     * 成功时候的调用
     * */
    public static <T> Result<T> success(T data){
        return new  Result<T>(data);
    }
    private Result(T data) {
        this.code = 0;
        this.msg = "success";
        this.data = data;
    }
    /**
     * 失败时候的调用
     * */
    public static <T> Result<T> error(ErrorCodeMsg cm){
        return new  Result<T>(cm);
    }
    private Result(ErrorCodeMsg cm) {
        if(cm == null) {
            return;
        }
        this.code = cm.getCode();
        this.msg = cm.getMsg();
    }
}


用到了 ErrorCodeMsg

package com.artisan.product.vo;
import lombok.Getter;
@Getter
public class ErrorCodeMsg {
    private int code;
    private String msg;
    // 异常
    public static ErrorCodeMsg SERVER_ERROR = new ErrorCodeMsg(-1, "服务端异常");
    private ErrorCodeMsg(int code, String msg) {
        this.code = code;
        this.msg = msg;
    }
}


ProductVO :返回给前台的商品信息格式,包含目录信息

package com.artisan.product.vo;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import java.util.List;
@Data
public class ProductVO {
    //  @JsonProperty注解用于属性上,作用是把该属性的名称序列化为另外一个名称,
    // 如把categoryName属性序列化为name
    // 【这里约定给前台返回的节点名为name, 但是为了方便理解这个name到底是什么的name,在vo中定义了方便理解的属性名】
    @JsonProperty("name")
    private String categoryName;
    @JsonProperty("type")
    private Integer categoryType;
    // 因为这个节点下可能返回多个ProductInfoVO,因此定义一个List集合
    @JsonProperty("products")
    private List<ProductInfoVO> productInfoVOList ;
}

ProductInfoVO 具体产品的数据VO

package com.artisan.product.vo;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import java.math.BigDecimal;
@Data
public class ProductInfoVO {
    @JsonProperty("id")
    private String productId;
    @JsonProperty("name")
    private String productName;
    @JsonProperty("price")
    private BigDecimal productPrice;
    @JsonProperty("description")
    private String productDescription;
    @JsonProperty("icon")
    private String productIcon;
}


Controller层逻辑


分析约定的前后台交互的JSON格式:

  • 每个ProductVO中我们需要获取产品目录名称及产品目录的category_type ,
    调用ProductCategoryService#categoryService方法即可。categoryService
  • 的入参为categoryTypeList,因此需要调用ProductService#getAllUpProduct获取所有上架商品对应的categoryType.
  • 获取到了后台的数据后,按照约定的格式拼装返回JSON串即可


package com.artisan.product.controller;
import com.artisan.product.domain.Product;
import com.artisan.product.domain.ProductCategory;
import com.artisan.product.service.ProductCategoryService;
import com.artisan.product.service.ProductService;
import com.artisan.product.vo.ProductInfoVO;
import com.artisan.product.vo.ProductVO;
import com.artisan.product.vo.Result;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
@RestController
@RequestMapping("/product")
public class ProductController {
    @Autowired
    private ProductService productService;
    @Autowired
    private ProductCategoryService categoryService;
    @GetMapping("/list")
    private Result list() {
        //1. 查询所有在架的商品
        List<Product> productInfoList = productService.getAllUpProduct();
        //2. 获取类目type列表
        List<Integer> categoryTypeList = productInfoList.stream()
                .map(Product::getCategoryType)
                .collect(Collectors.toList());
        //3. 从数据库查询类目
        List<ProductCategory> categoryList = categoryService.findByCategoryTypeIn(categoryTypeList);
        //4. 构造数据
        List<ProductVO> productVOList = new ArrayList<>();
        for (ProductCategory productCategory : categoryList) {
            ProductVO productVO = new ProductVO();
            // 设置属性
            productVO.setCategoryName(productCategory.getCategoryName());
            productVO.setCategoryType(productCategory.getCategoryType());
            // ProductInfoVO 集合
            List<ProductInfoVO> productInfoVOList = new ArrayList<>();
            for (Product product : productInfoList) {
                // 挂到对应的的categoryType下
                if (product.getCategoryType().equals(productCategory.getCategoryType())) {
                    ProductInfoVO productInfoVO = new ProductInfoVO();
                    // 将属性copy到productInfoVO,避免逐个属性set,更简洁
                    BeanUtils.copyProperties(product, productInfoVO);
                    productInfoVOList.add(productInfoVO);
                }
            }
            productVO.setProductInfoVOList(productInfoVOList);
            productVOList.add(productVO);
        }
        return Result.success(productVOList);
    }
}

启动测试

访问 http://localhost:8080/product/list

{
    "code": 0,
    "msg": "success",
    "data": [
        {
            "name": "热饮",
            "type": 99,
            "products": [
                {
                    "id": "1",
                    "name": "拿铁咖啡",
                    "price": 20.99,
                    "description": "咖啡,提神醒脑",
                    "icon": null
                },
                {
                    "id": "3",
                    "name": "卡布奇诺",
                    "price": 15,
                    "description": "卡布奇诺的香味",
                    "icon": null
                }
            ]
        },
        {
            "name": "酒水",
            "type": 98,
            "products": [
                {
                    "id": "2",
                    "name": "青岛纯生",
                    "price": 7.5,
                    "description": "啤酒",
                    "icon": null
                }
            ]
        }
    ]
}


格式化看下更加直观:

20190323013106955.png


知识点总结

Java8的Stream

 //2. 获取类目type列表
 List<Integer> categoryTypeList = productInfoList.stream()
         .map(Product::getCategoryType)
         .collect(Collectors.toList());


使用Java8中的Stream可以方便的对集合对象进行各种便利、高效的聚合操作,或者大批量数据操作。


20190323100357413.png


map生成的是个一对一映射,相当于for循环


20190323102613338.png


注意:流只能使用一次,使用结束之后,这个流就无法使用了。

点击查看更多示例


Beanutils.copyProperties( )

  // 将属性copy到productInfoVO,避免逐个属性set,更简洁
  BeanUtils.copyProperties(product, productInfoVO);

org.springframework.beans.BeanUtils# copyProperties作用是将一个Bean对象中的数据封装到另一个属性结构相似的Bean对象中。


同时org.apache.commons.beanutils.BeanUtils也有个copyProperties

需要注意的是这俩的copyProperties方法参数位置不同

 org.springframework.beans.BeanUtils#copyProperties(sourceDemo, targetDemo)
 org.apache.commons.beanutils.BeanUtils#copyProperties(targetDemo, sourceDemo)


Github地址


https://github.com/yangshangwei/springcloud-o2o/tree/master/artisan-product


相关文章
|
11月前
|
负载均衡 监控 Java
Spring Cloud Gateway 全解析:路由配置、断言规则与过滤器实战指南
本文详细介绍了 Spring Cloud Gateway 的核心功能与实践配置。首先讲解了网关模块的创建流程,包括依赖引入(gateway、nacos 服务发现、负载均衡)、端口与服务发现配置,以及路由规则的设置(需注意路径前缀重复与优先级 order)。接着深入解析路由断言,涵盖 After、Before、Path 等 12 种内置断言的参数、作用及配置示例,并说明了自定义断言的实现方法。随后重点阐述过滤器机制,区分路由过滤器(如 AddRequestHeader、RewritePath、RequestRateLimiter 等)与全局过滤器的作用范围与配置方式,提
Spring Cloud Gateway 全解析:路由配置、断言规则与过滤器实战指南
|
监控 Java API
Spring Boot 3.2 结合 Spring Cloud 微服务架构实操指南 现代分布式应用系统构建实战教程
Spring Boot 3.2 + Spring Cloud 2023.0 微服务架构实践摘要 本文基于Spring Boot 3.2.5和Spring Cloud 2023.0.1最新稳定版本,演示现代微服务架构的构建过程。主要内容包括: 技术栈选择:采用Spring Cloud Netflix Eureka 4.1.0作为服务注册中心,Resilience4j 2.1.0替代Hystrix实现熔断机制,配合OpenFeign和Gateway等组件。 核心实操步骤: 搭建Eureka注册中心服务 构建商品
1517 3
|
人工智能 搜索推荐 Java
Spring AI与DeepSeek实战三:打造企业知识库
本文基于Spring AI与RAG技术结合,通过构建实时知识库增强大语言模型能力,实现企业级智能搜索场景与个性化推荐,攻克LLM知识滞后与生成幻觉两大核心痛点。
1733 7
|
10月前
|
监控 Cloud Native Java
Spring Boot 3.x 微服务架构实战指南
🌟蒋星熠Jaxonic,技术宇宙中的星际旅人。深耕Spring Boot 3.x与微服务架构,探索云原生、性能优化与高可用系统设计。以代码为笔,在二进制星河中谱写极客诗篇。关注我,共赴技术星辰大海!(238字)
1428 2
Spring Boot 3.x 微服务架构实战指南
|
人工智能 Java API
Spring AI 实战|Spring AI入门之DeepSeek调用
本文介绍了Spring AI框架如何帮助Java开发者轻松集成和使用大模型API。文章从Spring AI的初探开始,探讨了其核心能力及应用场景,包括手动与自动发起请求、流式响应实现打字机效果,以及兼容不同AI服务(如DeepSeek、通义千问)的方法。同时,还详细讲解了如何在生产环境中添加监控以优化性能和成本管理。通过Spring AI,开发者可以简化大模型调用流程,降低复杂度,为企业智能应用开发提供强大支持。最后,文章展望了Spring AI在未来AI时代的重要作用,鼓励开发者积极拥抱这一技术变革。
4579 71
Spring AI 实战|Spring AI入门之DeepSeek调用
|
10月前
|
XML Java 测试技术
《深入理解Spring》:IoC容器核心原理与实战
Spring IoC通过控制反转与依赖注入实现对象间的解耦,由容器统一管理Bean的生命周期与依赖关系。支持XML、注解和Java配置三种方式,结合作用域、条件化配置与循环依赖处理等机制,提升应用的可维护性与可测试性,是现代Java开发的核心基石。
|
安全 Java 数据库
Spring Security 实战指南:从入门到精通
本文详细介绍了Spring Security在Java Web项目中的应用,涵盖登录、权限控制与安全防护等功能。通过Filter Chain过滤器链实现请求拦截与认证授权,核心组件包括AuthenticationProvider和UserDetailsService,负责用户信息加载与密码验证。文章还解析了项目结构,如SecurityConfig配置类、User实体类及自定义登录逻辑,并探讨了Method-Level Security、CSRF防护、Remember-Me等进阶功能。最后总结了Spring Security的核心机制与常见配置,帮助开发者构建健壮的安全系统。
2570 0
|
存储 Java 数据库
Spring Boot 注册登录系统:问题总结与优化实践
在Spring Boot开发中,注册登录模块常面临数据库设计、密码加密、权限配置及用户体验等问题。本文以便利店销售系统为例,详细解析四大类问题:数据库字段约束(如默认值缺失)、密码加密(明文存储风险)、Spring Security配置(路径权限不当)以及表单交互(数据丢失与提示不足)。通过优化数据库结构、引入BCrypt加密、完善安全配置和改进用户交互,提供了一套全面的解决方案,助力开发者构建更 robust 的系统。
537 0
|
12月前
|
人工智能 监控 安全
如何快速上手【Spring AOP】?核心应用实战(上篇)
哈喽大家好吖~欢迎来到Spring AOP系列教程的上篇 - 应用篇。在本篇,我们将专注于Spring AOP的实际应用,通过具体的代码示例和场景分析,帮助大家掌握AOP的使用方法和技巧。而在后续的下篇中,我们将深入探讨Spring AOP的实现原理和底层机制。 AOP(Aspect-Oriented Programming,面向切面编程)是Spring框架中的核心特性之一,它能够帮助我们解决横切关注点(如日志记录、性能统计、安全控制、事务管理等)的问题,提高代码的模块化程度和复用性。