我正在使用Redis的Spring Boot并使用以下配置:
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.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import redis.clients.jedis.JedisPoolConfig;
@Configuration
public class RedisConfig {
@Bean
public RedisConnectionFactory redisConnectionFactory() {
JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMaxTotal(5);
poolConfig.setTestOnBorrow(true);
poolConfig.setTestOnReturn(true);
JedisConnectionFactory connectionFactory = new JedisConnectionFactory(poolConfig);
connectionFactory.setUsePool(true);
connectionFactory.setHostName("localhost");
connectionFactory.setPort(6379);
return connectionFactory;
}
@Bean
public RedisTemplate redisTemplate() {
RedisTemplate redisTemplate = new RedisTemplate();
redisTemplate.setConnectionFactory(redisConnectionFactory());
redisTemplate.setEnableTransactionSupport(true);
return redisTemplate;
}
@Bean
public StringRedisTemplate stringRedisTemplate() {
StringRedisTemplate stringRedisTemplate = new StringRedisTemplate(redisConnectionFactory());
stringRedisTemplate.setEnableTransactionSupport(true);
return stringRedisTemplate;
}
}
RedisRepository.java
public class RedisRepository<T> {
@Resource(name="redisTemplate")
private HashOperations<String, String, T> hashOps;
@SuppressWarnings("unchecked")
public void addObjectInMemory(String key,String hashKey, T t) {
hashOps.put(key, hashKey, t);
}
public T getEntity(String key,String hashKey){
return hashOps.get(key, hashKey);
}
}
我正在使用以下代码调用put和get方法
@Autowired
RedisRepository redisRepository;
private static final String ISP_KEY="ISPKEY";
private static final String REG_HIST_KEY="REGHISTKEY";
@Override
public void onApplicationEvent(final ApplicationReadyEvent event) {
System.out.println("APPLICATION HAS STARTED !!!!!!!!!!!!!!!!!!!!!!!!!!");
List<SrsFreeIsps> freeIsps=freeIspRepository.findAll();
for(SrsFreeIsps isp:freeIsps){
redisRepository.addObjectInMemory(ISP_KEY, isp.getEmailDomain(),
isp);
}
List<RegistrationHistograms> registrationHistograms=
registrationHistogramRepo.findAll();
for(RegistrationHistograms reg:registrationHistograms){
redisRepository.addObjectInMemory(REG_HIST_KEY,
reg.getOrganizationId(), reg);
}
//For testing..To be removed
SrsFreeIsps isp= (SrsFreeIsps) redisRepository.getEntity(ISP_KEY,
freeIsps.get(0).getEmailDomain());
}
hashOps.get(key,hashKey)它引发以下异常:
JedisDataException: ERR Operation against a key holding the wrong kind of value
hashOps.put(key,hashKey,t)正常工作。
T是我在Redis中坚持存在的实体。