最近在学习redis,使用spring-data-redis的RedisTemplate.delete()方法删除时,添加是成功的,但是不能删除。
代码如下
public abstract class AbstractBaseRedisDao {
@Autowired
protected RedisTemplate redisTemplate;
// public void setRedisTemplate(RedisTemplate redisTemplate) {
// this.redisTemplate = redisTemplate;
// }
public RedisSerializer getRedisSerializer() {
return redisTemplate.getStringSerializer();
}
}
public interface IUserDao {
boolean add(User user);
void delete(String key);
void delete(List keys);
User get(String keyId);
}
@Service
public class UserDao extends AbstractBaseRedisDao implements IUserDao {
public boolean add(final User user) {
boolean result = redisTemplate.execute(new RedisCallback() {
public Boolean doInRedis(RedisConnection redisConnection) throws DataAccessException {
RedisSerializer serializer = getRedisSerializer();
byte[] key = serializer.serialize(user.getId());
byte[] name = serializer.serialize(user.getName());
return redisConnection.setNX(key, name);
}
});
return result;
}
public void delete(String key) {
List list = new ArrayList();
list.add(key);
delete(list);
}
public void delete(List keys) {
redisTemplate.delete(keys);
}
public User get(final String keyId) {
User result = redisTemplate.execute(new RedisCallback() {
public User doInRedis(RedisConnection redisConnection) throws DataAccessException {
RedisSerializer serializer = getRedisSerializer();
byte[] key = serializer.serialize(keyId);
byte[] value = redisConnection.get(key);
if (value == null) {
return null;
}
String name = serializer.deserialize(value);
return new User(keyId, name, null);
}
});
return result;
}
}
配置如下:
测试用例:
public class RedisTest {
private IUserDao userDao;
@Before
public void init() {
ApplicationContext ctx = new ClassPathXmlApplicationContext("case1/applicationContext.xml");
userDao = (IUserDao) ctx.getBean("userDao");
}
@Test
public void testAddUser() {
User user = new User();
user.setId("B");
user.setName("B");
boolean result = userDao.add(user);
Assert.assertTrue(result);
}
@Test
public void testDelete() {
String key = "B";
User user = userDao.get(key);
System.out.println("删除前:" + user);
userDao.delete(key);
user = userDao.get(key);
System.out.println("删除后:" + user);
}
}
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
请问解决了吗? 我也遇到这个问题了, 也不报错. 就是没有删除.
我解决了,我的key拼错了.