Previously in the SpringBoot project, I used RedisTemplate to manipulate data in Redis, which is officially supported by Spring. Compared to Spring Data’s support for MongoDB and ES, this approach to using Template is really not elegant! Redis ORM framework RedisOM is a Redis ORM framework RedisOM is a Redis ORM framework RedisOM is a Redis ORM framework RedisOM is a Redis ORM framework RedisOM

SpringBoot e-commerce project mall (50K + STAR) address: github.com/macrozheng/…

RedisOM profile

RedisOM is an ORM framework officially released by Redis, which is an extension of Spring Data Redis. Since Redis already supports storing native JSON objects, the previous approach of using RedisTemplate to store JOSN objects directly as strings was obviously not elegant. With RedisOM, we can not only manipulate the data in Redis in the form of objects, but also achieve the search function!

11 JDK installation

Since RedisOM currently only supports JDK 11 and above, we need to install it before using it.

  • downloadJDK 11It’s recommended hereTsinghua University open source software mirror stationDownload:Mirrors.tuna.tsinghua.edu.cn/AdoptOpenJD…

  • Download the package version and decompress it to the specified directory.

  • Then in the project configuration of IDEA, set the JDK dependent version of the corresponding module asJDK 11Can.

use

Next, we take managing the product information stored in Redis as an example to realize the product search function. Note that the entire version of Redis RedisMod is installed. For details, please refer to the RediSearch tutorial.

  • First of all inpom.xmlAdd RedisOM dependencies to the
<! --Redis OM dependencies -->
<dependency>
    <groupId>com.redis.om</groupId>
    <artifactId>redis-om-spring</artifactId>
    <version>0.3.0 - the SNAPSHOT</version>
</dependency>
Copy the code
  • Because RedisOM only has the snapshot version, you need to add the snapshot repository.
<repositories>
    <repository>
        <id>snapshots-repo</id>
        <url>https://s01.oss.sonatype.org/content/repositories/snapshots/</url>
    </repository>
</repositories>
Copy the code
  • Then in the configuration fileapplication.ymlAdd Redis connection configuration to
spring:
  redis:
    host: 192.1683.105. # Redis server address
    database: 0 # Redis database index (default 0)
    port: 6379 # Redis server connection port
    password: # Redis server connection password (default null)
    timeout: 3000ms Connection timeout
Copy the code
  • Then add it to the startup class@EnableRedisDocumentRepositoriesAnnotations enable RedisOM’s document repository and configure the path to the document repository.
@SpringBootApplication
@EnableRedisDocumentRepositories(basePackages = "com.macro.mall.tiny.*")
public class MallTinyApplication {

    public static void main(String[] args) { SpringApplication.run(MallTinyApplication.class, args); }}Copy the code
  • Then create the document object for the product, using@DocumentAnnotations identify it as a document object, and since our search information contains Chinese, we need to set the language tochinese;
/** * Created by macro on 2021/10/12. */
@Data
@EqualsAndHashCode(callSuper = false)
@Document(language = "chinese")
public class Product {
    @Id
    private Long id;
    @Indexed
    private String productSn;
    @Searchable
    private String name;
    @Searchable
    private String subTitle;
    @Indexed
    private String brandName;
    @Indexed
    private Integer price;
    @Indexed
    private Integer count;
}
Copy the code
  • Introduce the function of several comments in the code.
    • @Id: declares the primary key, RedisOM will passThe full name of the class: IDKeys like this to store data;
    • @Indexed: declares an index, usually for non-text types;
    • @Searchable: Declares an index that can be searched, usually for text types.
  • Next, create a document repository interface, inheritedRedisDocumentRepositoryInterface;
/** * Repository * Created by macro on 2022/3/1. */
public interface ProductRepository extends RedisDocumentRepository<Product.Long> {}Copy the code
  • Create Controller for test, passRepositoryTo achieve the Redis data creation, deletion, query and paging functions;
/** * Created by macro on 2022/3/1. */
@RestController
@API (tags = "ProductController", description = "Redis OM ")
@RequestMapping("/product")
public class ProductController {

    @Autowired
    private ProductRepository productRepository;

    @apiOperation (" Import goods ")
    @PostMapping("/import")
    public CommonResult importList(a) {
        productRepository.deleteAll();
        List<Product> productList = LocalJsonUtil.getListFromJson("json/products.json", Product.class);
        for (Product product : productList) {
            productRepository.save(product);
        }
        return CommonResult.success(null);
    }

    @apiOperation (" Create commodity ")
    @PostMapping("/create")
    public CommonResult create(@RequestBody Product entity) {
        productRepository.save(entity);
        return CommonResult.success(null);
    }

    @ ApiOperation (" delete ")
    @PostMapping("/delete/{id}")
    public CommonResult delete(@PathVariable Long id) {
        productRepository.deleteById(id);
        return CommonResult.success(null);
    }

    @apiOperation (" Query single ")
    @GetMapping("/detail/{id}")
    public CommonResult<Product> detail(@PathVariable Long id) {
        Optional<Product> result = productRepository.findById(id);
        return CommonResult.success(result.orElse(null));
    }

    @apiOperation (" paging query ")
    @GetMapping("/page")
    public CommonResult<List<Product>> page(@RequestParam(defaultValue = "1") Integer pageNum,
                                            @RequestParam(defaultValue = "5") Integer pageSize) {
        Pageable pageable = PageRequest.of(pageNum - 1, pageSize);
        Page<Product> pageResult = productRepository.findAll(pageable);
        returnCommonResult.success(pageResult.getContent()); }}Copy the code
  • When we start the project, we can see that RedisOM automatically indexes the documents;

  • Next we visit Swagger for testing, using firstImport goodsInterface to import data, access address:http://localhost:8088/swagger-ui/

  • After the import is successful, we can see that RedisOM has inserted native JSON data into RedisThe full name of the class: IDTo name the keys and store all ids in a SET;

  • We can query commodity information by ID;

  • Of course, RedisOM also supports derivative queries. We created a method name that automatically implements query logic, such as searching for products by brand name, searching for products by name and subtitle keywords.
/** * Repository * Created by macro on 2022/3/1. */
public interface ProductRepository extends RedisDocumentRepository<Product.Long> {
    /** * query by brand name */
    List<Product> findByBrandName(String brandName);

    /** * search */ by name or subtitle
    List<Product> findByNameOrSubTitle(String name, String subTitle);
}
Copy the code
  • You can add the following interfaces to the Controller for testing.
/** * Created by macro on 2022/3/1. */
@RestController
@API (tags = "ProductController", description = "Redis OM ")
@RequestMapping("/product")
public class ProductController {

    @Autowired
    private ProductRepository productRepository;

    @apiOperation (" Query by brand ")
    @GetMapping("/getByBrandName")
    public CommonResult<List<Product>> getByBrandName(String brandName) {
        List<Product> resultList = productRepository.findByBrandName(brandName);
        return CommonResult.success(resultList);
    }

    @apiOperation (" Search by name or subtitle ")
    @GetMapping("/search")
    public CommonResult<List<Product>> search(String keyword) {
        List<Product> resultList = productRepository.findByNameOrSubTitle(keyword, keyword);
        returnCommonResult.success(resultList); }}Copy the code
  • We can query products by brand name;

  • You can also search for products by keyword;

  • What are the rules for this type of derived query that automatically implements query logic based on method names? Please refer to the following table for details.

conclusion

I tried RedisOM today, and it’s really elegant, similar to how Spring Data works with MongoDB and ES. However, RedisOM has only released a snapshot version so far, looking forward to a Release, which will reportedly support JDK 8!

If you want to learn more about Redis, you can try the full Redis program (50K+Star) at github.com/macrozheng/…

The resources

  • Project address: github.com/redis/redis…
  • The official document: developer.redis.com/develop/jav…

Project source code address

Github.com/macrozheng/…