Still using RedisTemplate? Try Redis's official ORM framework. It's elegant enough to use

Previously, in the SpringBoot project, I have been using RedisTemplate to operate the data in Redis, which is also the way officially supported by Spring. Compared with Spring Data's support for MongoDB and ES, this way of using Template is really not elegant! Recently, RedisOM, Redis's exclusive ORM framework, has been officially launched by Redis. It's elegant enough to use. I recommend it to you!

RedisOM introduction

RedisOM is an ORM framework officially launched by Redis and an extension of Spring Data Redis. Since Redis currently supports the storage of native JSON objects, the previous way of using RedisTemplate to store JOSN objects directly with strings is obviously not elegant. Through RedisOM, we can not only operate the data in Redis in the form of objects, but also realize the search function!

JDK 11 installation

At present, RedisOM only supports JDK 11 or above, so we have to install it before using it.

  • First, Download JDK 11. It is recommended to download it from the open source software mirror station of Tsinghua University. The download address is: https://mirrors.tuna.tsinghua.edu.cn/AdoptOpenJDK/11/jdk/x64/

  • Download the compressed package version, and then unzip it to the specified directory;

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

use

Next, we take managing the commodity information stored in Redis as an example to realize the commodity search function. Note that after installing the full version of RedisMod, you can refer to the RediSearch tutorial for details.

  • First in POM Add RedisOM related dependencies in XML;
<!--Redis OM Related dependency-->
<dependency>
    <groupId>com.redis.om</groupId>
    <artifactId>redis-om-spring</artifactId>
    <version>0.3.0-SNAPSHOT</version>
</dependency>
  • Since RedisOM only has snapshot version at present, it is necessary to add snapshot warehouse;
<repositories>
    <repository>
        <id>snapshots-repo</id>
        <url>https://s01.oss.sonatype.org/content/repositories/snapshots/</url>
    </repository>
</repositories>
  • Then in the configuration file application Add Redis connection configuration in YML;
spring:
  redis:
    host: 192.168.3.105 # Redis server address
    database: 0 # Redis database index (0 by default)
    port: 6379 # Redis server connection port
    password: # Redis server connection password (blank by default)
    timeout: 3000ms # Connection timeout
  • Then add the @ enablereredisdocumentrepositories annotation on the startup class, enable RedisOM's document warehouse function, and configure the path where the document warehouse is located;
@SpringBootApplication
@EnableRedisDocumentRepositories(basePackages = "com.macro.mall.tiny.*")
public class MallTinyApplication {

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

}
  • Then create the Document object of the commodity and use the @ Document annotation to identify it as a Document object. Since our search information contains chinese, we need to set the language to chinese;
/**
 * Commodity entity class
 * 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;
}
  • Introduce the functions of several annotations in the code;
    • @ID: declare the primary key. RedisOM will store data through keys such as full class name: ID;
    • @Indexed: declared index, usually used on non text types;
    • @Searchable: declares the index that can be searched, which is usually used on text types.
  • Next, create a document warehouse interface and inherit the RedisDocumentRepository interface;
/**
 * Commodity management Repository
 * Created by macro on 2022/3/1.
 */
public interface ProductRepository extends RedisDocumentRepository<Product, Long> {
}
  • Create a Controller for testing, and realize the functions of creating, deleting, querying and paging data in Redis through Repository;
/**
 * Manage products using Redis OM
 * Created by macro on 2022/3/1.
 */
@RestController
@Api(tags = "ProductController", description = "use Redis OM Manage goods")
@RequestMapping("/product")
public class ProductController {

    @Autowired
    private ProductRepository productRepository;

    @ApiOperation("Import goods")
    @PostMapping("/import")
    public CommonResult importList() {
        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 item")
    @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);
        return CommonResult.success(pageResult.getContent());
    }

}
  • When we start the project, we can find that RedisOM will automatically index the documents;

  • Next, we visit Swagger to test. First, we use the import goods interface to import data. The access address is: http://localhost:8088/swagger-ui/

  • After successful import, we can find that RedisOM has inserted native JSON data into Redis, named the key in the form of full class name: ID, and stored all IDS in a SET set;

  • We can query commodity information through ID;

  • Of course, RedisOM also supports derivative query. The query logic can be automatically realized through the method name we created, such as querying products according to brand name and searching products according to name and subtitle keywords;
/**
 * Commodity management 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);
}
  • The following interfaces can be added to the Controller for testing;
/**
 * Manage products using Redis OM
 * Created by macro on 2022/3/1.
 */
@RestController
@Api(tags = "ProductController", description = "use Redis OM Manage goods")
@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);
        return CommonResult.success(resultList);
    }

}
  • We can inquire about products by brand name;

  • You can also search for goods through keywords;

  • What are the rules for this kind of derivative query that automatically implements the query logic according to the method name? For details, please refer to the following table.

summary

Today, I experienced a RedisOM, which is really elegant enough to use. It is similar to using Spring Data to operate MongoDB and ES. At present, however, RedisOM has only released the snapshot version and is looking forward to the Release version. It is said that the Release version will support JDK 8!

Keywords: Java Redis Spring Boot Programmer

Added by JustFoo on Thu, 10 Mar 2022 07:49:55 +0200