SpringBootWeb 篇-深入了解 Redis 五种类型命令与如何在 Java 中操作 Redis
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
@Component
public class RedisCommandExample {
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Autowired
private RedisTemplate<String, Object> redisTemplate;
public void setStringValue() {
stringRedisTemplate.opsForValue().set("stringKey", "stringValue");
}
public void getStringValue() {
String value = stringRedisTemplate.opsForValue().get("stringKey");
System.out.println("String Value: " + value);
}
public void setObjectValue() {
User user = new User("user1", 25);
redisTemplate.opsForValue().set("userKey", user);
}
public void getObjectValue() {
User user = (User) redisTemplate.opsForValue().get("userKey");
System.out.println("Object Value: " + user.getName());
}
public void incrementValue() {
long newValue = stringRedisTemplate.opsForValue().increment("counterKey", 5);
System.out.println("Incremented Value: " + newValue);
}
public void appendValue() {
stringRedisTemplate.opsForValue().append("stringKey", "AppendValue");
String value = stringRedisTemplate.opsForValue().get("stringKey");
System.out.println("Appended Value: " + value);
}
}
class User {
private String name;
private int age;
public User(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
这个代码示例展示了如何在Spring Boot项目中使用StringRedisTemplate
和RedisTemplate<String, Object>
操作Redis。其中包含了设置字符串、对象,以及使用Redis的五种基本类型命令(GET, SET, INCR, APPEND)的例子。这些操作可以在任何需要与Redis交互的Spring Boot应用中使用。
评论已关闭