springboot使用redis

springboot使用redis

1.开启redis

2.导入依赖

就只需要这一个依赖!不需要spring-boot-starter-cache

  <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
  </dependency>

当你导入这一个依赖时,SpringBoot的CacheManager就会使用RedisCache。

如果你的Redis使用默认配置,这时候已经可以启动程序了。

3.配置Redis

# Redis数据库索引(默认为0)
spring.redis.database=1
# Redis服务器地址
spring.redis.host=127.0.0.1
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=1000
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.pool.max-idle=10
# 连接池中的最小空闲连接
spring.redis.pool.min-idle=2
# 连接超时时间(毫秒)
spring.redis.timeout=0

4.模板编程

    @Autowired
    private StringRedisTemplate stringRedisTemplate;//操作key-value都是字符串
 
    @Autowired
    private RedisTemplate redisTemplate;//操作key-value都是对象
 
    /**
     *  Redis常见的五大数据类型:
     *  stringRedisTemplate.opsForValue();[String(字符串)]
     *  stringRedisTemplate.opsForList();[List(列表)]
     *  stringRedisTemplate.opsForSet();[Set(集合)]
     *  stringRedisTemplate.opsForHash();[Hash(散列)]
     *  stringRedisTemplate.opsForZSet();[ZSet(有序集合)]
     */
    public void test(){
        stringRedisTemplate.opsForValue().append("msg","hello");
    }

5.简单使用

//用的hutool
@Autowired
    private StringRedisTemplate stringRedisTemplate;//操作key-value都是字符串
	
	public static final string files_key="FILES_FRONT_ALL";

	@GetMapping("/index")
public Resut index(){
  String jsonStr=  stringRedisTemplate.opsForValue().get(FILES_KEY)
	List<Files> files;
    if(StrUtil.isBlannk(jsonStr)){
        files = fileMapper.selectList(null) ;// 查询数据库数据
    	//缓存到redis 注意 保存的是JSON格式
        stringRedisTemplate.opsForValue().set(FILES_KEY,JSONUtil.toJSONStr(files));
    }else{
        files =JSONUtil.toBean(jsonStr,new TypeReference<List<Files>>(){},true);
    }
    return Result.success(files);
}


//解决增删改缓存没及时刷新的问题
//方案一
执行增删改之前删除当前key,查询那重新添加key
    
   private void flusRedis(String key){
    stringRedisTemplate.delete(key);
}
//方案二
查询数据库新的数据,重新设置key
    private void setCache(String key,String value){  
    stringRedisTemplate.opsForValue().set(key,value);  
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值