springboot(8)--集成redis

0.maven依赖

<dependency>
    <groupId>org.springframework</groupId>
    <artifact>spring-boot-starter</artifact>
</dependency>

1.在application.properties配置redis

这里写的都是默认配置:

spring.redis.database=0
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=
spring.redis.jedis.pool.max-active=8
spring.redis.jedis.pool.max-wait=-1
spring.redis.jedis.pool.max-idle=8
spring.redis.jedis.pool.min-idle=0
spring.redis.timeout=0

2.配置StringRedisTemplate Bean

@Configuration
public class RedisConfig {
     
    /**
     *  定义 StringRedisTemplate ,指定序列化和反序列化的处理类
     * @param factory
     * @return
     */
    @Bean
    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
        StringRedisTemplate template = new StringRedisTemplate(factory);
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(
                Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        //序列化 值时使用此序列化方法
        template.setValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }
}

3.使用redis

@RestController
@Api(tags="Redis 测试")
@RequestMapping(value="/redis")
public class RedisController{
    
    private String StringRedisTemplate redisTemplate;

    @PostMapping(value="/set")
    @ApiOperation("存值")
    public String set(@Valid@RequestParam String key,@Valid@RequestParam String value){
        redisTemplate.opsForValue().set(key,value);
        Map<String, Object> result=new HashMap<>();
        result.put("code","111");
        result.put("msg","set successful!");
        return result;
    }
    
    @GetMapping(value="/get")
    @ApiOperation("获取值")
    public String get(@Valid@RequestParam String key){
        Map<String,Object> result=new HashMap<>();
        result.put("result","key="+key+"value"+redisTemplate.opsForValue().get(key));
        result.put("msg","get successful!");
        return result;
    }

}      

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值