SpringBoot2集成RediSearch
Spring Boot 2整合RediSearch,需要使用Spring Data Redis和Jedis两个库。
- 在pom.xml中添加依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson-spring-boot-starter</artifactId>
<version>3.16.2</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>2.6.2</version>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>3.7.0</version>
</dependency>
</dependencies>
- 配置Redis和Redisson客户端
@Configuration
public class RedisConfig {
@Bean
public JedisConnectionFactory jedisConnectionFactory() {
RedisStandaloneConfiguration serverConfig = new RedisStandaloneConfiguration("localhost", 6379);
return new JedisConnectionFactory(serverConfig);
}
@Bean
public RedissonClient redissonClient() {
Config config = new Config();
config.useSingleServer().setAddress("redis://127.0.0.1:6379");
return Redisson.create(config);
}
}
- 使用RedissonClient和Spring Data Redis操作RediSearch
@Service
public class RedisSearchService {
@Autowired
private RedissonClient redissonClient;
@Autowired
private StringRedisTemplate stringRedisTemplate;
public void createIndex() {
// 创建索引
RKeys keys = redissonClient.getKeys();
if (keys.delete("redisearchIndex") == 1) {
System.out.println("Index has been deleted");
}
// 创建索引
RIndex<Object, Object> index = redissonClient.getIndex("redisearchIndex", options -> {
options.indexOptions(IndexOptions.defaultOptions());
options.setLang(Lang.PUBLISH);
});
index.addEntry("key", "value");
}
public void searchIndex() {
// 搜索索引
RIndex<Object, Object> index = redissonClient.getIndex("redisearchIndex");
// 使用RediSearch查询语言
Query query = new Query("@key:*").limit(10);
List<Entry<Object, Object>> entries = index.execute(query);
for (Entry<Object, Object> entry : entries) {
System.out.println(entry.getKey())
评论已关闭