Spring Boot 整合 Redis

1.配置文件

spring.redis.host= 127.0.0.1
## Redis服务器连接端口
spring.redis.port=6379
## 连接超时时间(毫秒)
spring.redis.timeout= 30
## Redis服务器连接密码(默认为空)
#spring.redis.password =
## 连接池中的最大连接数
spring.redis.jedis.pool.max-active= 10
## 连接池中的最大空闲连接
spring.redis.jedis.pool.max-idle= 8
## 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.jedis.pool.max-wait=10ms

2.RedisConfig.java


/**
 * Created By Diko
 * Time:2019/8/6 15:40
 * E-mail:kedongyu@sina.cn
 * Function:
 */
@Configuration
public class RedisConfig {

    @Bean
    public  RedisTemplate<String, Object> redisTemplateKeyString(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }

}

3.测试


/**
 * Created By Diko
 * Time:2019/8/6 15:06
 * E-mail:kedongyu@sina.cn
 * Function:
 */
@RestController
@RequestMapping("/redis")
public class RedisController {
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @RequestMapping("/add")
    public void add(Student student){
        redisTemplate.opsForValue().set(String.valueOf(student.getNum()),student);
        redisTemplate.opsForHash().put(Student.class.getName(),String.valueOf(student.getNum()),student);
    }

    @RequestMapping("/get")
    public Student get(String num){
        return (Student)redisTemplate.opsForHash().get(Student.class.getName(),num);
    }
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值