谷粒商城学习笔记,第八天:缓存SpringCache+商品检索模型

99封情书 提交于 2020-11-18 17:46:16

谷粒商城学习笔记,第八天:缓存SpringCache+商品检索模型

一、SpringCache

SpringCache文档地址

SpringCache本质上不是一个具体的缓存实现方案(比如EHCache 或者 OSCache),而是一个对缓存使用的抽象,通过在既有代码中加入少量它定义的各种 annotation,即能够达到缓存方法的返回对象的效果。

SpringCache定义了Cache和CacheManager接口来统一不同的缓存技术,并支持JCache注解来简化我们的开发。

##Cache接口
   cache接口为缓存的组件规范定义,包含缓存的各种操作集合。
   cache接口下提供了xxxCache的实现:如RedisCache、EhCacheCache、ConcurrentMapCache等

常用注解:

@EnableCaching:开启缓存功能

@Cacheable:将数据保存到缓存

@CachePut:不影响方法执行更新缓存

@CacheEvict:将数据从缓存中删除

@Caching:组合以上多个操作:cacheable+cacheput+cacheEvict

@CacheConfig:在class类级别,共享缓存配置

1、整合

springcache+redis

引入依赖:

<!--springcache-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>

<!--reids-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
    <!--排除lettuce-->
    <exclusions>
        <exclusion>
            <groupId>io.lettuce</groupId>
            <artifactId>lettuce-core</artifactId>
        </exclusion>
    </exclusions>
</dependency>

<!--引入jedis-->
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
</dependency>

<!--以后使用redission作为分布式锁,分布式对象等功能框架-->
<dependency>
    <groupId>org.redisson</groupId>
    <artifactId>redisson</artifactId>
    <version>3.12.0</version>
</dependency>

配置:CacheAutoConfiguration

##CacheAutoConfiguration会自动导入RedisCacheConfiguration
##RedisCacheConfiguration自动配置了RedisCacheManager缓存管理器


spring: 
  ##配置使用redis作为缓存
  cache: 
  	type: redis
  	redis:
  	 ##TTL时间
  	 time-to-live: 3600000
  	 ##如果指定了缓存前缀就使用我们指定的,如果没有指定默认使用缓存的名字作为前缀(如下面的category)
  	 key-prefix: PRODUCT_
  	 ##是否开启缓存前缀,如果false就不使用【任何】前缀
  	 use-key-prefix: true
  	 ##是否缓存空值NULL,防止缓存穿透
  	 cache-null-value: true
  ##redis的配置
  redis:
    # 地址
    host: localhost
    # 端口,默认为6379
    port: 6379
    # 密码
    password: admin123
    ##foobared
    # 连接超时时间
    timeout: 10s

开启缓存功能

//开启缓存功能springcache
@EnableCaching
//打开服务注册和发现
@EnableDiscoveryClient
@SpringBootApplication
public class GulimallProductApplication {

    public static void main(String[] args) {
        SpringApplication.run(GulimallProductApplication.class, args);
    }

}

测试,使用

/**
 * 1>、每一个需要缓存的数据我们都要指定放到哪个名字的缓存下【缓存分区{按照业务类型}】
 * 2>、代表当前方法的结果需要缓存,
       如果方法中有,方法不需要调用。
 *     如果方法中没有,会调用方法,最后将方法结果放入缓存
 */
@Cacheable({"catogory"})
@Override
public List<CategoryEntity> listLevel1Category() {
    List<CategoryEntity> categoryEntities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_id", 1));
    return categoryEntities;
}

2、Cacheable

@Cacheable 添加缓存

##@Cacheable默认行为:
	##1)、如果缓存中有,方法不调用
	##2)、key默认自动生成,缓存的名字::SimpleKey[](自动生成的KEY值)
	##3)、缓存的value值,默认使用JDK序列化机制,将序列化后的数据保存到redis中
	##4)、默认TTL时间为-1(永久存在)
/**     
  * 3>、自定义:
  *         value:缓存分区
  *         key: redis的key,接收一个SPEL表达式,所以直接用字符串需要加""引号
  *         TTL:spirng.cache.redis.time-to-live = 3600000,在配置文件中配置
  *         sync:会加本地锁synchronized,防止缓存击穿
  */
@Cacheable(value={"catogory"},key = "'level1Category'",sync = true)
@Override
public List<CategoryEntity> listLevel1Category() {
    List<CategoryEntity> categoryEntities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_id", 1));
    return categoryEntities;
}

3、cacheEvict 和 Caching

@CacheEvict 删除缓存

##使用:删除缓存需要指明 缓存分区和key

##删除单个缓存:
@CacheEvict(value="category",key="'level1Category'")

##删除多个缓存:
@Caching(Evict={
	@CacheEvict(value="category",key="'level1Category'"),
    @CacheEvict(value="category",key="'allCategory'")
})

##删除分区下所有数据
@CacheEvict(value="category",allEntries=true)

4、cacheput

@Cacheput是修改数据
##在双写模式下使用,即修改了数据库后同时修改缓存

##如果返回值null,下次进行该key值查询时,还会查一次数据库,此时相当于@CacheEvict注解

##如果返回值不为null,此时会进行该key值缓存的更新,更新缓存值为返回的数据;

二、商品检索模型

1、页面检索格式:

keyword=小米&sort=saleCount_desc/asc&hasStock=0/1&skuPrice=400_1900&brandId=1&catalog3Id=1&attrs=1_3G:4G:5G&attrs=2_骁龙845&attrs=4_高清屏

2、Java模型

//除了keyword在must中{参与评分},其他全是filter{不参与评分}
@Data
public class SearchParam {

    /**
     * 页面传递过来的全文匹配关键字
     */
    private String keyword;
    /**
     * 三类分级Id
     */
    private Long catalog3Id;
    /**
     * 排序条件
     * sort=saleCount_asc/desc
     * sort=skuPrice_asc/desc
     * sort=hotScore_asc/desc
     */
    private String sort;
    /**
     * 是否有货 hasStock=0/1
     * 0无货1有货
     */
    private Integer hasStock;
    /**
     * 价格区间  skuPrice=1_500/_500/500_
     * 1到500
     * 低于500
     * 高于500
     */
    private String skuPrice;
    /**
     * 品牌brandId=2
     */
    private List<Long> brandId;
    /**
     * 属性:attrs=2_5寸:6寸
     * attr的ID为2的属性
     * 5寸或者6寸
     */
    private List<String> attrs;
    /**
     * 页码
     */
    private Integer pageNum;
}

3、返回数据模型:

@Data
public class SearchResult{
    
    //查询到的所有商品信息
    private List<SkuEsModel> products;
    
    /**
     * 分页信息
     **/
    //当前页码
    private Integer pageNum;
    //总记录数
    private Long total;
    //总页码
    private Integer totalPages;
    
    /**
     * 再次检索条件
     **/
    //当前查询到的结果,所有设计到的品牌信息
    private List<BrandVo> brands;
    //当前查询到的结果,所有设计到的属性信息
    private List<AttrVo> attrs;
    //当前查询到的结果,所有设计到的分类信息
    private List<CatalogVo> catalogs;
    
    
    
    @Data
    public static class BrandVo{
        //品牌ID
        private Long brandId;
        //品牌名称
        private String brandName;
        //品牌图片
        private String brandImg;
    }
    
    @Data
    public static class AttrVo{
        //属性ID
        private Long attrId;
        //属性名称
        private String attrName;
        //属性值
        private List<String> attrValue;
    }
    
    @Data
    public static class CatalogVo{
        //分类ID
        private Long catalogId;
        //分类名称
        private String catalogName;
    }
    
}

4、检索:

@Service
public class MallSearchServiceImpl implements MallSearchService {

    @Autowired
    RestHighLevelClient restHighLevelClient;

    @Override
    public SearchResult search(SearchParam param) {
        //动态构建查询DSL语句
        SearchResult result = null;

        //准备检索请求
        SearchRequest searchRequest = buildSearchRequest(param);

        try {
            //执行检索请求
            SearchResponse searchResponse = restHighLevelClient.search(searchRequest, EsConfig.COMMON_OPTIONS);

            //分析响应数据封装成我们所需要的格式
            result = buildSearchResult(searchResponse, param);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return result;
    }
    /**
     * 准备检索请求
     * 模糊匹配 、过滤、(按照属性、分类、品牌、价格区间、库存)、排序、分页、高亮、聚合分析
     *
     * @return
     */
    private SearchRequest buildSearchRequest(SearchParam param) {
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        /**
         * 模糊匹配 、过滤、(按照属性、分类、品牌、价格区间、库存)
         */
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        if (StringUtils.isNotBlank(param.getKeyword()))
            boolQuery.must(QueryBuilders.matchQuery("skuTitle", param.getKeyword()));
        if (param.getCatalog3Id() != null)
            boolQuery.filter(QueryBuilders.termQuery("catalogId", param.getCatalog3Id()));
        if (param.getBrandId() != null && param.getBrandId().size() > 0)
            boolQuery.filter(QueryBuilders.termsQuery("brandId", param.getBrandId()));
        if (param.getHasStock() != null)
            boolQuery.filter(QueryBuilders.termQuery("hasStock", param.getHasStock() == 1));
        if (StringUtils.isNotBlank(param.getSkuPrice())) {
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("skuPrice");
            String[] s = param.getSkuPrice().split("_");
            if (s.length == 2) {
                rangeQuery.gte(s[0]).lte(s[1]);
            } else if (s.length == 1) {
                if (param.getSkuPrice().startsWith("_"))
                    rangeQuery.lte(s[1]);
                if (param.getSkuPrice().endsWith("_"))
                    rangeQuery.gte(s[0]);
            }
            boolQuery.filter(rangeQuery);
        }
        if (param.getAttrs() != null && param.getAttrs().size() > 0) {
            //attrs=1_5寸:8寸&attrs2_16G:8G
            for (String attr : param.getAttrs()) {
                String[] s = attr.split("_");
                String attrId = s[0];//检索的属性id
                String[] attrValues = s[1].split(":");
                BoolQueryBuilder nestedBoolQuery = QueryBuilders.boolQuery();
                nestedBoolQuery.must(QueryBuilders.termQuery("attrs.attrId", attrId));
                nestedBoolQuery.must(QueryBuilders.termsQuery("attrs.attrValue", attrValues));
                //每一个都得生成一个nested查询
                NestedQueryBuilder nestedQuery = QueryBuilders.nestedQuery("attrs", nestedBoolQuery, ScoreMode.None);
                boolQuery.filter(nestedQuery);
            }
        }

        //所有条件进行封装
        sourceBuilder.query(boolQuery);
        /**
         * 排序、分页、高亮
         */
        if (StringUtils.isNotBlank(param.getSort())) {
            String sort = param.getSkuPrice();
            String[] s = sort.split("_");
            SortOrder sortOrder = s[1].equalsIgnoreCase("asc") ? SortOrder.ASC : SortOrder.DESC;
            sourceBuilder.sort(s[0], sortOrder);
        }

        System.out.println("PageNum" + param.getPageNum());

        if (param.getPageNum() == null) {
            //sourceBuilder.from((50 - 1) * EsConstant.PRODUCT_PAGESIZE);
        } else {
            sourceBuilder.from((param.getPageNum() - 1) * EsConstant.PRODUCT_PAGESIZE);
        }
        sourceBuilder.size(EsConstant.PRODUCT_PAGESIZE);

        if (StringUtils.isNotBlank(param.getKeyword())) {
            HighlightBuilder builder = new HighlightBuilder();
            builder.field("skuTitle");
            builder.preTags("<b style='color:red'>");
            builder.postTags("</b>");
            sourceBuilder.highlighter(builder);
        }
        /**
         * 聚合分析
         */
        //品牌聚合
        TermsAggregationBuilder brand_agg = AggregationBuilders.terms("brand_agg").field("brandId").size(50);
        //品牌聚合的子聚合
        brand_agg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(1));
        brand_agg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(1));
        sourceBuilder.aggregation(brand_agg);

        //分类聚合
        TermsAggregationBuilder catalog_agg = AggregationBuilders.terms("catalog_agg").field("catalogId").size(50);
        sourceBuilder.aggregation(catalog_agg);
        //分类子聚合
        catalog_agg.subAggregation(AggregationBuilders.terms("catalog_name_agg").field("catalogName").size(1));

        //属性聚合
        NestedAggregationBuilder attr_agg = AggregationBuilders.nested("attr_agg", "attrs");
        TermsAggregationBuilder attr_id_agg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId");
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(1));
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(1));
        attr_agg.subAggregation(attr_id_agg);

        //聚合attr
        sourceBuilder.aggregation(attr_agg);

        System.out.println("检索请求" + sourceBuilder.toString());

        SearchRequest searchRequest = new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX}, sourceBuilder);
        return searchRequest;

    }

    /**
     * 构建结果数据
     * 模糊匹配,过滤(按照属性、分类、品牌,价格区间,库存),完成排序、分页、高亮,聚合分析功能
     * @param response
     * @return
     */
    private SearchResult buildSearchResult(SearchResponse response,SearchParam param) {

        SearchResult result = new SearchResult();

        //1、返回的所有查询到的商品
        SearchHits hits = response.getHits();
        List<SkuEsModel> esModels = new ArrayList<>();

        //遍历所有商品信息
        if (hits.getHits() != null && hits.getHits().length > 0) {
            for (SearchHit hit : hits.getHits()) {
                String sourceAsString = hit.getSourceAsString();
                SkuEsModel esModel = JSON.parseObject(sourceAsString, SkuEsModel.class);

                //判断是否按关键字检索,若是就显示高亮,否则不显示
                if (!StringUtils.isEmpty(param.getKeyword())) {
                    //拿到高亮信息显示标题
                    HighlightField skuTitle = hit.getHighlightFields().get("skuTitle");
                    String skuTitleValue = skuTitle.getFragments()[0].string();
                    esModel.setSkuTitle(skuTitleValue);
                }
                esModels.add(esModel);
            }
        }
        result.setProducts(esModels);

        //2、当前商品涉及到的所有属性信息
        List<SearchResult.AttrVo> attrVos = new ArrayList<>();
        //获取属性信息的聚合
        ParsedNested attrsAgg = response.getAggregations().get("attr_agg");
        ParsedLongTerms attrIdAgg = attrsAgg.getAggregations().get("attr_id_agg");
        for (Terms.Bucket bucket : attrIdAgg.getBuckets()) {

            SearchResult.AttrVo attrVo = new SearchResult.AttrVo();

            //1、得到属性的id
            long attrId = bucket.getKeyAsNumber().longValue();
            attrVo.setAttrId(attrId);

            //2、得到属性的名字
            ParsedStringTerms attrNameAgg = bucket.getAggregations().get("attr_name_agg");
            String attrName = attrNameAgg.getBuckets().get(0).getKeyAsString();
            attrVo.setAttrName(attrName);

            //3、得到属性的所有值
            ParsedStringTerms attrValueAgg = bucket.getAggregations().get("attr_value_agg");
            List<String> attrValues = attrValueAgg.getBuckets().stream().map(item -> item.getKeyAsString()).collect(
                    Collectors.toList());
            attrVo.setAttrValue(attrValues);

            attrVos.add(attrVo);
        }

        result.setAttrs(attrVos);

        //3、当前商品涉及到的所有品牌信息
        List<SearchResult.BrandVo> brandVos = new ArrayList<>();
        //获取到品牌的聚合
        ParsedLongTerms brandAgg = response.getAggregations().get("brand_agg");
        for (Terms.Bucket bucket : brandAgg.getBuckets()) {
            SearchResult.BrandVo brandVo = new SearchResult.BrandVo();

            //1、得到品牌的id
            long brandId = bucket.getKeyAsNumber().longValue();
            brandVo.setBrandId(brandId);

            //2、得到品牌的名字
            ParsedStringTerms brandNameAgg = bucket.getAggregations().get("brand_name_agg");
            String brandName = brandNameAgg.getBuckets().get(0).getKeyAsString();
            brandVo.setBrandName(brandName);

            //3、得到品牌的图片
            ParsedStringTerms brandImgAgg = bucket.getAggregations().get("brand_img_agg");
            String brandImg = brandImgAgg.getBuckets().get(0).getKeyAsString();
            brandVo.setBrandImg(brandImg);

            brandVos.add(brandVo);
        }
        result.setBrands(brandVos);

        //4、当前商品涉及到的所有分类信息
        //获取到分类的聚合
        List<SearchResult.CatalogVo> catalogVos = new ArrayList<>();
        ParsedLongTerms catalogAgg = response.getAggregations().get("catalog_agg");
        for (Terms.Bucket bucket : catalogAgg.getBuckets()) {
            SearchResult.CatalogVo catalogVo = new SearchResult.CatalogVo();
            //得到分类id
            String keyAsString = bucket.getKeyAsString();
            catalogVo.setCatalogId(Long.parseLong(keyAsString));

            //得到分类名
            ParsedStringTerms catalogNameAgg = bucket.getAggregations().get("catalog_name_agg");
            String catalogName = catalogNameAgg.getBuckets().get(0).getKeyAsString();
            catalogVo.setCatalogName(catalogName);
            catalogVos.add(catalogVo);
        }

        result.setCatalogs(catalogVos);
        //===============以上可以从聚合信息中获取====================//
        //5、分页信息-页码
        result.setPageNum(param.getPageNum());
        //5、1分页信息、总记录数
        long total = hits.getTotalHits().value;
        result.setTotal(total);

        //5、2分页信息-总页码-计算
        int totalPages = (int)total % EsConstant.PRODUCT_PAGESIZE == 0 ?
                (int)total / EsConstant.PRODUCT_PAGESIZE : ((int)total / EsConstant.PRODUCT_PAGESIZE + 1);
        result.setTotalPages(totalPages);
        return result;
    }
}

5、ES模型映射:

PUT mall_product
{
  "mappings": {
    "properties": {
      "attrs": {
        "type": "nested",
        "properties": {
          "attrId": {
            "type": "long"
          },
          "attrName": {
            "type": "keyword"
          },
          "attrValue": {
            "type": "keyword"
          }
        }
      },
      "brandId": {
        "type": "long"
      },
      "brandImg": {
        "type": "keyword"
      },
      "brandName": {
        "type": "keyword"
      },
      "catalogId": {
        "type": "long"
      },
      "catalogName": {
        "type": "keyword"
      },
      "hasStock": {
        "type": "boolean"
      },
      "hotScore": {
        "type": "long"
      },
      "saleCount": {
        "type": "long"
      },
      "skuId": {
        "type": "long"
      },
      "skuImg": {
        "type": "keyword"
      },
      "skuPrice": {
        "type": "keyword"
      },
      "skuTitle": {
        "type": "text",
        "analyzer": "ik_smart"
      },
      "spuId": {
        "type": "keyword"
      }
    }
  }
}

6、DSL语句

GET /mall_product/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "title": {
              "query": "手机",
              "operator": "and"
            }
          }
        }
      ],
      "filter": [
        {
          "nested": {
            "path": "attrs",
            "query": {
              "bool": {
                "must": [
                  {
                    "term": {
                      "attrs.attrId": {
                        "value": "9"
                      }
                    }
                  },
                  {
                    "terms": {
                      "attrs.attrValue": ["5","6","7"]
                    }
                  }
                ]
              }
            }
          }
        },
        {
          "nested": {
            "path": "attrs",
            "query": {
              "bool": {
                "must": [
                  {
                    "term": {
                      "attrs.attrId": {
                        "value": "4"
                      }
                    }
                  },
                  {
                    "terms": {
                      "attrs.attrValue": ["8G", "12G"]
                    }
                  }
                ]
              }
            }
          }
        },
        {
          "terms": {
            "brandId": [1,2,3]
          }
        },
        {
          "terms": {
            "categoryId": [225]
          }
        },
        {
          "range": {
            "price": {
              "gte": 0,
              "lte": 10000
            }
          }
        }
      ]
    }
  },
  "from": 0,
  "size": 10,
  "highlight": {
    "fields": {
      "name": {}
    },
    "pre_tags": "<b style='color:red'>",
    "post_tags": "</b>"
  },
  "sort": [
    {
      "price": {
        "order": "desc"
      }
    }
  ],
  "aggs": {
    "attr_agg": {
      "nested": {
        "path": "attrs"
      },
      "aggs": {
        "attrIdAgg": {
          "terms": {
            "field": "attrs.attrId"
          },
          "aggs": {
            "attrNameAgg": {
              "terms": {
                "field": "attrs.attrName"
              }
            },
            "attrValueAgg": {
              "terms": {
                "field": "attrs.attrValue"
              }
            }
          }
        }
      }
    },
    "brandIdAgg": {
      "terms": {
        "field": "brandId"
      },
      "aggs": {
        "brandNameAgg": {
          "terms": {
            "field": "brandName"
          }
        }
      }
    },
    "categoryIdAgg": {
      "terms": {
        "field": "categoryId"
      },
      "aggs": {
        "categoryNameAgg": {
          "terms": {
            "field": "categoryName"
          }
        }
      }
    }
  }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!