用SpringBoot整合redis实现简单增删改查操作的代码
时间: 2024-05-11 08:16:14 浏览: 93
好的,以下是使用SpringBoot整合Redis实现简单增删改查操作的代码示例:
1.首先,在pom.xml文件中添加Redis和Spring Data Redis的依赖:
```
<!-- Redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
```
2.在application.properties文件中配置Redis的连接信息:
```
spring.redis.host=localhost # Redis服务器地址
spring.redis.port=6379 # Redis服务器端口
```
3.创建一个RedisConfig配置类,用于配置Redis连接池和RedisTemplate:
```
@Configuration
public class RedisConfig {
@Bean
public JedisConnectionFactory jedisConnectionFactory() {
JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory();
jedisConnectionFactory.setHostName("localhost"); // Redis服务器地址
jedisConnectionFactory.setPort(6379); // Redis服务器端口
return jedisConnectionFactory;
}
@Bean
public RedisTemplate<String, Object> redisTemplate() {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(jedisConnectionFactory());
redisTemplate.setDefaultSerializer(new StringRedisSerializer()); // key的序列化方式
redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<>(Object.class)); // value的序列化方式
return redisTemplate;
}
@Bean
public RedisCacheManager redisCacheManager() {
return RedisCacheManager.create(jedisConnectionFactory());
}
}
```
4.创建一个User实体类,用于测试Redis的增删改查操作:
```
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User implements Serializable {
private static final long serialVersionUID = 1L;
private String id;
private String name;
private Integer age;
}
```
5.创建一个UserController类,用于测试Redis的增删改查操作:
```
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
@PostMapping
public String add(@RequestBody User user) {
redisTemplate.opsForValue().set(user.getId(), user);
return "success";
}
@GetMapping("/{id}")
public User get(@PathVariable String id) {
return (User) redisTemplate.opsForValue().get(id);
}
@PutMapping
public String update(@RequestBody User user) {
redisTemplate.opsForValue().set(user.getId(), user);
return "success";
}
@DeleteMapping("/{id}")
public String delete(@PathVariable String id) {
redisTemplate.delete(id);
return "success";
}
}
```
以上就是使用SpringBoot整合Redis实现简单增删改查操作的代码示例,希望能够帮助到你。
阅读全文