Reputation: 959
I have set one key in redis using redis-as below
redis 127.0.0.1:6379> set 100.vo.t1 '{"foo": "bar", "ans": 42}'
OK
redis 127.0.0.1:6379> get 100.vo.t1
"{\"foo\": \"bar\", \"ans\": 42}"
But now i am trying to read the same usin Spring boot and Jedis but the value is coming as null
Rrepository
@Repository
public class TemplateRepositoryImpl implements TemplateRepository {
private ValueOperations<String, Object> valueOperations;
private RedisTemplate<String, Object> redisTemplate;
@Autowired
public TemplateRepositoryImpl(RedisTemplate<String, Object> redisTemplate) {
this.redisTemplate = redisTemplate;
}
@PostConstruct
private void init() {
valueOperations = redisTemplate.opsForValue();
}
@Override
public String getTemplateSequenceinString(String key) {
System.out.println("the key recieved is " + key);
return (String) valueOperations.get(key);
}
}
Controller
@Controller
@RequestMapping("/ts")
public class MainController {
@Autowired
private TemplateRepository tmpl;
@GetMapping("/initiate/{templateName}")
public String getTemplate(Model model, @PathVariable("templateName") String templateName) throws IOException {
String key = "100.vo.t1" ;
System.out.println("The answer is "+tmpl.getTemplateSequenceinString(key));
return templateName;
}
}
RedisConfig
@Configuration
@ComponentScan("com.ts.templateService")
public class RedisConfig_1 {
@Bean
JedisConnectionFactory jedisConnectionFactory() {
JedisConnectionFactory jedisConFactory
= new JedisConnectionFactory();
jedisConFactory.setHostName("localhost");
jedisConFactory.setPort(6379);
return jedisConFactory;
}
@Bean
public RedisTemplate<String, Object> redisTemplate() {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(jedisConnectionFactory());
return template;
}
}
Upvotes: 1
Views: 2160
Reputation: 349
The key here is the Serializer
, RedisTemplate
's default serializer is JdkSerializationRedisSerializer
, you should use StringRedisSerializer
.
@Bean
public RedisTemplate<String, Object> redisTemplate() {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setDefaultSerializer(new StringRedisSerializer()); // set here
template.setConnectionFactory(jedisConnectionFactory());
return template;
}
Upvotes: 1