写一个spring-boot-starter-data-redis 的demo
时间: 2023-07-29 16:11:00 浏览: 52
当然,我可以为你提供一个Spring Boot Starter Data Redis的Demo。以下是一个简单的演示:
首先,确保你已经在你的项目中添加了`spring-boot-starter-data-redis`依赖。
接下来,创建一个Redis配置类,比如`RedisConfig`:
```java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericToStringSerializer;
@Configuration
public class RedisConfig {
@Bean
public RedisConnectionFactory redisConnectionFactory() {
return new LettuceConnectionFactory();
}
@Bean
public RedisTemplate<String, Object> redisTemplate() {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory());
redisTemplate.setValueSerializer(new GenericToStringSerializer<>(Object.class));
return redisTemplate;
}
}
```
然后,创建一个简单的控制器类,比如`RedisController`:
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class RedisController {
private final RedisTemplate<String, Object> redisTemplate;
@Autowired
public RedisController(RedisTemplate<String, Object> redisTemplate) {
this.redisTemplate = redisTemplate;
}
@GetMapping("/set/{key}/{value}")
public void setValue(@PathVariable String key, @PathVariable String value) {
redisTemplate.opsForValue().set(key, value);
}
@GetMapping("/get/{key}")
public Object getValue(@PathVariable String key) {
return redisTemplate.opsForValue().get(key);
}
}
```
最后,启动你的Spring Boot应用程序,并通过以下URL进行测试:
设置值:`http://localhost:8080/set/{key}/{value}`
获取值:`http://localhost:8080/get/{key}`
请确保替换`{key}`和`{value}`为实际的键和值。
这只是一个简单的示例,你可以根据你的需求进一步扩展和定制。希望对你有所帮助!