Spring Boot 是时下流行的 Java 平台开发框架,其提供了 spring-boot-starter-data-redis 库,该库提供了高级的API接口,使我们可以像使用数据库接口(Repository)那样来操作 Redis 中的数据。
加入依赖库
首先,在 Spring Boot 项目中加入以下依赖:
1 2 3 4 5 6 7 8 9 10 11
| <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
<dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>3.3.0</version> <type>jar</type> </dependency>
|
为方便对实体类的读写,我一般也加入 Lombok 库,如下:
1 2 3 4 5 6
| <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.12</version> <scope>provided</scope> </dependency>
|
定义配置类
我们使用类代码来实现 Redis 的配置, 代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| @Bean public JedisConnectionFactory jedisConnectionFactory() {
RedisStandaloneConfiguration config = new RedisStandaloneConfiguration(); config.setHostName("localhost"); config.setPort(6379);
JedisConnectionFactory factory = new JedisConnectionFactory(config); return factory; }
@Bean public RedisTemplate<String, Object> redisTemplate() { RedisTemplate<String, Object> template = new RedisTemplate<>(); template.setConnectionFactory(jedisConnectionFactory()); return template; }
|
定义需要缓存的对象
将需要缓存的数据定义为实体对象,代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13
| @Data @AllArgsConstructor @NoArgsConstructor @RedisHash("Device") public class Device implements Serializable {
private String id;
private String title;
private Boolean online;
}
|
注意: 上面的代码中使用了 RedisHash 注解
定义对应的仓库
和关系数据库的 ORM 类似,我们定义一个 Repository 类, 代码如下:
1 2 3
| @Repository public interface DeviceRepository extends CrudRepository<Device, String> { }
|
因为继承至 CrudRepository, 所以 DeviceRepository 类具备基本的增、删、查、改 功能。
存取数据
基于上面的准备,我们就可以在需要使用 Redis 的地方使用对应的方法了:
- 把数据存入 Redis 中,使用类似下面的代码:
1 2
| Device device = new Device("device-01", "Light", false); deviceRepository.save(device);
|
- 按 Key 查找数据
1
| Optional<Device> device = deviceRepository.findById(id);
|
- 修改存在数据
1 2 3 4 5
| Optional<Device> device = deviceRepository.findById(id); if (device.isPresent()) { device.setTitle("New Title"); deviceRepository.save(device); }
|
实际上可以看出,只要 id 能匹配上,save 方法能用于更新已有的数据。
- 删除数据
1
| deviceRepository.deleteById(id);
|