使用Spring Boot从Redis读取字符串

时间:2018-06-25 06:30:45

标签: java spring redis jedis

我已使用redis在redis中设置了一个键,如下所示

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}"

但是现在我正在尝试在Spring Boot和Jedis中读取相同的内容,但其值将为null

存储库

@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
@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;
    }
}

1 个答案:

答案 0 :(得分:0)

这里的密钥是SerializerRedisTemplate的默认序列化器是JdkSerializationRedisSerializer,您应该使用StringRedisSerializer

@Bean
public RedisTemplate<String, Object> redisTemplate() {

    RedisTemplate<String, Object> template = new RedisTemplate<>();
    template.setDefaultSerializer(new StringRedisSerializer()); // set here
    template.setConnectionFactory(jedisConnectionFactory());
    return template;
}