Springboot-整合redis数据库(作为缓存,作为分布式锁)

springboot对redis的操作封装了两个StringRedisTemplate和RedisTemplate类,StringRedisTemplate是RedisTemplate的子类,StringRedisTemplate它只能存储字符串类型,无法存储对象类型。要想用StringRedisTemplate存储对象必须把对象转为json字符串。

一、StringRedisTemplate

前提:一定要保证redis数据库开启

StringRedisTemplate的使用:

1.引入相关依赖

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

2.创建一个测试类并注入StringRedisTemplate对象

 @Autowired
        private StringRedisTemplate stringRedisTemplate;

3.编写配置文件

#你的IP
spring.redis.host=192.168.40.199
#你的端口
spring.redis.port=6379

4. 使用StringRedisTemplate

该类把对每种数据类型的操作,单独封了相应的内部类。

        //1.对字符串类型的操作
        stringRedisTemplate.opsForValue();
        //2.对hash类型的操作
        stringRedisTemplate.opsForHash();
        //3.对list类型的操作
        stringRedisTemplate.opsForList();
        //4.对set类型的操作
        stringRedisTemplate.opsForSet();
        //5.对有序set的操作
        stringRedisTemplate.opsForZSet();

只介绍两种:String类型的操作,Hash类型的操作

(1)对String类型的操作

  //查看所有的key
        Set<String> keys = stringRedisTemplate.keys("*");
        System.out.println(keys);
      /*  //删除指定的key
        stringRedisTemplate.delete("k1");
        //查看key是否存在
        stringRedisTemplate.hasKey("k2");*/
        //1.调用封装的String类型的内部类操作字符串
        ValueOperations<String, String> forValue = stringRedisTemplate.opsForValue();
        //存入字符串类型数据
        forValue.set("k1","张三");
        //存入固定时间的数据,时间到期数据失效
        forValue.set("k2","李四",30, TimeUnit.MILLISECONDS);
        //存入数据如果没有就存入,存入成功返回true,失败返回false
        Boolean aBoolean = forValue.setIfAbsent("k3", "王五", 60, TimeUnit.SECONDS);
        System.out.println(aBoolean);
        //在数据后追加数据
        forValue.append("k1","牛啊");
        //通过key获取数据
        String k1 = forValue.get("k1");
        System.out.println(k1);

(2)对 hash类型的数据的操作

  //对hash类型的操作
        HashOperations<String, Object, Object> forHash = stringRedisTemplate.opsForHash();
        //向指定hash存入单个key和valu
        forHash.put("k4","name","小张");
        forHash.put("k4","age","19");
        //向指定hash中存入多个key,value
        Map<String,String> map=new HashMap<>();
        map.put("name","小王");
        map.put("age","22");
        forHash.putAll("k5",map);
        //获取指定key的value
        Object o = forHash.get("k4", "name");
        System.out.println(o);
        //获取指定hash的全部key
        Set<Object> k5 = forHash.keys("k5");
        System.out.println(k5);
        //获取指定hash的全部value
        List<Object> values = forHash.values("k5");
        System.out.println(values);

二、 RedisTemplate

RedisTemplate的使用:

 RedisTemplate默认使用的是 JdkSerializationRedisSerializer,存入数据时,会将数据先序列化成字节数组,然后再存入 Redis 数据库。

1.注入RedisTemplate对象

@Autowired
    private RedisTemplate redisTemplate=new RedisTemplate();

2.使用

ValueOperations forValue = redisTemplate.opsForValue();
        //对字符串类型的操作
        forValue.set("k1","张三",30,TimeUnit.SECONDS);
        //对hash类型的操作
        HashOperations forHash = redisTemplate.opsForHash();
        forHash.put("k2","name","李四");
        forHash.put("k2","age","22");

3.出现的问题:

 我们查看使用RedisTemplate存储的数据可以看到发生了编码格式的错误

原因:

RedisTemplate默认使用的是 JdkSerializationRedisSerializer

存入数据时,会将数据先序列化成字节数组,然后再存入 Redis 数据库。

解决办法:

当我们存储数据时一定要指定序列化方法

      //指定序列化方法
        redisTemplate.setKeySerializer(new StringRedisSerializer());//为key指定
        redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<Object>(Object.class));

 但是我们上面的RedisTemplate需要每次都指定key value以及field的序列化方式。

这样会非常麻烦我们也可以创建一个配置类,为RedisTemplate指定好序列化。以后再用就无需指定。

package com.gsh.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @Auther: haohao
 * @Date:2022/8/220:09
 */
@Configuration
public class RedisConif {
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        RedisSerializer<String> redisSerializer = new StringRedisSerializer();
        Jackson2JsonRedisSerializer 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.setConnectionFactory(factory);
        //key序列化方式
        template.setKeySerializer(redisSerializer);
        //value序列化
        template.setValueSerializer(jackson2JsonRedisSerializer);
        //value hashmap序列化  filed value
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        template.setHashKeySerializer(redisSerializer);
        return template;
    }
}


三、Redis作为缓存

1.redis作为缓存的优点:

数据存储在内存中,数据查询速度快。可以分摊数据库压力。

2.什么样的数据适合放入缓存

查询频率比较高,修改频率比较低。

安全系数低的数据

3.使用注解来开启缓存

在Service业务层使用

@Service
public class DeptService {
    @Autowired
    //注入deptmapper
    private DeptMapper deptMapper;
    @Autowired
    //注入redisTemplate
    private RedisTemplate redisTemplate;
    //业务代码

    //根据id查询单个信息

    /**
     *Cacheable注解:cacheNames:表示缓存的名称 key:唯一标识
     * 这个注解会先从缓存中查看key(cacheNames::key)是否存在,如果存在则不会执行方法体,
     * 如果不存在则执行方法体并把方法体的返回值存入到缓存
     */
    @Cacheable(cacheNames = {"dept"},key = "#id")
    public CommonResult findById(Integer id){
        Dept dept = deptMapper.selectById(id);
        System.out.println(dept);
        if (dept!=null){
            return new CommonResult(2000,"查询成功!",dept);
        }
        return new CommonResult(5000,"查询失败!",null);
    }
    //
    @CacheEvict(cacheNames = {"dept"}, key = "#id")
    /**
     * CacheEvict注解会先删除缓存然后再执行方法体
     */
    public CommonResult deleteById(Integer id){
        int row = deptMapper.deleteById(id);
        if(row>0){
            return new CommonResult(2000,"删除成功!",null);
        }
        return new CommonResult(5000,"删除失败!",null);
    }
    //
    @CachePut
    /**
     * CachePut会保证方法被执行,同时方法的返回值也会被存入到缓存中,实现缓存与数据库的同步更新
     */
    public CommonResult updateDept(Dept dept){
        int row = deptMapper.updateById(dept);
        if(row>0){
            return new CommonResult(2000,"修改成功!",dept);
        }
        return new CommonResult(5000,"修改失败!",null);
    }

}

四、Redis作为分布式锁

前提导入mp依赖

@Service
public class StockService {
    @Autowired
    private StockMapper stockMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    public String decreaseStock(Integer productld){
        ValueOperations forValue = redisTemplate.opsForValue();
        Boolean aBoolean = forValue.setIfAbsent("log::"+productld, "exists");
        if(aBoolean){
            try {
                //查看锁数量
                Stock stock = stockMapper.selectById(productld);
                Integer num = stock.getNum();
                if (num>0){
                    //每次减一
                    stock.setNum(num-1);
                    stockMapper.updateById(stock);
                    System.out.println("扣减数量成功!剩余库存:"+(num-1));
                    return "true";
                }else {
                    System.out.println("扣减数量失败!数量不足");
                }
            }finally {
                redisTemplate.delete("log::"+productld);
            }
        }
        return "服务器正在处理,请等待>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>";
    }
}

redis解决分布式锁的bug

解决方案:

可以使用:redission依赖,redission解决redis超时问题的原理。

为持有锁的线程开启一个守护线程,守护线程会每隔10秒检查当前线程是否还持有锁,如果持有则延迟生存时间。

 1.引入依赖

        <dependency>
            <groupId>org.redisson</groupId>
            <artifactId>redisson</artifactId>
            <version>3.13.4</version>
        </dependency>

2.spring容器管理redisson

    //获取redisson对象并交于spring容器管理
    @Bean
    public Redisson redisson(){
        Config config =new Config();
        config.useSingleServer().
                setAddress("redis://localhost:6379").
                //redis默认有16个数据库
                setDatabase(0);
        return (Redisson) Redisson.create(config);
    }

3.使用:

@Service
public class StockService_Redisson {
    @Autowired
    private StockMapper stockMapper;
    //注入redisson对象
    @Autowired
    private Redisson redisson;
    public String decreaseStock(Integer productld){
            //获取对象
        RLock lock = redisson.getLock("gsh::" + productld);
        try {
                lock.lock(30, TimeUnit.SECONDS);
                //查看锁数量
                Stock stock = stockMapper.selectById(productld);
                Integer num = stock.getNum();
                if (num>0){
                    //每次减一
                    stock.setNum(num-1);
                    stockMapper.updateById(stock);
                    System.out.println("扣减数量成功!剩余库存:"+(num-1));
                    return "true";
                }else {
                    System.out.println("扣减数量失败!数量不足");
                }
            }finally {
                lock.unlock();
            }
        return "服务器正在处理,请等待>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>";
    }
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值