前面已经介绍了,测试用户缓存的实现方式,本文介绍正式用户是怎么缓存的
正式用户是采用主级索引
+次级索引
的实现方式。
主级索引:存储所有次级索引的键,可以快速访问所有分类的用户;
次级索引:针对每个用户分类构建,存储属于该分类的用户列表。
使用场景
假设我们有一个电子商务平台,需要处理和查询大量的商品数据。
每个商品都有多个属性,例如品牌、类别、价格区间等。为了提高查询效率,
、我们决定使用Redis作为缓存层来构建主级和次级索引
import java.util.*;
import java.util.stream.Collectors;
import redis.clients.jedis.Jedis;
public class ECommerceIndexing {
private Jedis redisUtil = new Jedis("localhost", 6379);
//构建索引 productList:从 db 查询的商品列表
public void buildIndices(List<Product> productList) {
// 主级索引键
String primaryIndexKey = "product_indices";
// 按照商品分类构建次级索引
Map<String, List<Product>> categoryMap =
productList.stream().collect(Collectors.groupingBy(Product::getCategory));
// 构建次级索引并更新主级索引
categoryMap.forEach((category, products) -> {
String secondaryIndexKey = "category_" + category;
redisUtil.sadd(primaryIndexKey, secondaryIndexKey); // 添加到主级索引
// 添加到次级索引
products.forEach(product -> redisUtil.sadd(secondaryIndexKey, product.getId().toString()));
});
}
// 根据商品类型查找商品信息
public void queryProductsByCategory(String category) {
String secondaryIndexKey = "category_" + category;
Set<String> productIds = redisUtil.sscan(secondaryIndexKey);
for (String productId : productIds) {
// 根据商品ID从数据库或缓存中获取商品详情
Product product = getProductById(productId);
System.out.println(product);
}
}
// 得到所有的商品类型
public void queryAllCategories() {
// 直接查询主级索引获取所有分类
Set<String> categories = redisUtil.sscan("product_indices");
System.out.println("Available categories: " + categories);
}
// 假设这个方法从数据库获取商品详情
private Product getProductById(String productId) {
// 数据库查询逻辑
return new Product(); // 返回商品对象
}
// 假设这是商品实体类
public static class Product {
private String id;
private String category;
public String getId() {
return id;
}
public String getCategory() {
return category;
}
}
public static void main(String[] args) {
ECommerceIndexing indexing = new ECommerceIndexing();
List<Product> productList = Arrays.asList(
// 初始化商品列表
);
indexing.buildIndices(productList);
indexing.queryAllCategories();
indexing.queryProductsByCategory("Electronics"); // 查询电子产品分类
}
}
场景说明
-
构建索引:在
buildIndices
方法中,我们首先创建一个主级索引键product_indices
,然后遍历商品列表,按照商品分类将它们分组,并为每个分类创建一个次级索引。 -
查询特定分类:
queryProductsByCategory
方法展示了如何根据分类查询商品。它首先从主级索引中找到对应的次级索引键,然后从次级索引中获取所有商品ID,并查询每个商品的详细信息。 -
查询所有分类:
queryAllCategories
方法直接查询主级索引以获取所有可用的商品分类,这可以用于生成用户界面上的分类列表。 -
商品实体:
Product
类是一个简单的商品实体,包含商品ID和分类属性。 -
主函数:
main
方法演示了如何初始化商品列表,构建索引,并执行查询。