利用spring集成redis使用


前言

利用普通的Jedis类去操作redis数据库与spring集成redis数据库


一、利用Jedis类连接redis数据库操作

(1)引入依赖Jedis的jar包连接redis数据库

<!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
        <!--引入连接redis数据库的jar依赖坐标-->
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>3.6.0</version>
        </dependency>

(2)使用Jedis类连接redis数据库中的几种数据类型进行java代码编程操作

  • Redis字符串类型
 Jedis jedis=new Jedis("localhost",6379);
  String id = jedis.set("id", "1");
        String name = jedis.set("name", "王五");
        Long sex = jedis.setnx("sex", "男");
        String age = jedis.setex("age", 20L, "23");
        //控制台输出
        System.out.println("id = " + id);
        System.out.println("name = " + name);
        System.out.println("sex = " + sex);
        System.out.println("age = " + age);
           //获取redis数据库键对应的值
        System.out.println("id = " + jedis.get("id"));
        System.out.println("name = " + jedis.get("name"));
        System.out.println("sex = " + jedis.get("sex"));
        System.out.println("age = " + jedis.get("age"));
  • Redis的list列表类型
    Jedis jedis=new Jedis("localhost",6379);
   Long lpush=jedis.lpush("names","张三","李四","赵恒");
   Long rpush=jedis.rpush("names","张三1","李四1","赵恒1");
   //控制台输出
     System.out.println("lpush = " + lpush);
        System.out.println("rpush = " + rpush);
       //获取列表数据
        List<String> names = jedis.lrange("names", 0, -1);
        names.forEach(n-> System.out.println("n = " + n));

  • Redis的hash的map类型
		Jedis jedis=new Jedis("localhost",6379);
        Map<String,String> map=new HashMap<>();
        map.put("学号1","张一");
        map.put("学号2","张二");
        map.put("学号3","张三");
        //hmset方法是一次性可以插入多条数据
        String classes = jedis.hmset("classes1", map);


 Map<String,String> map1=new HashMap<>();
        map1.put("学号4","张四");
        /*map.put("学号2","张二");
        map.put("学号3","张三");*/
        //hset方法是只能插入一条数据
        Long classes1 = jedis.hset("classes2", map1);
//输出每一个键对应的值的Map集合
 System.out.println("classes = " + classes);
 System.out.println("classes1 = " + classes1);
 
//获取map和map1的键对应的值遍历
 Map<String, String> cla = jedis.hgetAll("classes1");
        cla.forEach((k,v) ->{
            System.out.println("k= " + v);
        });
        System.out.println("=======================");
        Map<String, String> cla1 = jedis.hgetAll("classes2");
        cla1.forEach((k,v) ->{
            System.out.println("k= " + v);
        });


  • 最后一个需要关闭连接
 //关闭数据库
        jedis.close();

二、测试redis数据库操作的性能

public class Test1 {
    public static void main(String[] args) {
        Jedis jedis=new Jedis("localhost",6379);
        long start = System.currentTimeMillis();
        long i=0L;
        while (true){
            long end = System.currentTimeMillis();
            if (end-start>=1000){
               break;
            }
            //i++;
            //处理redis数据
            jedis.set("key"+(++i),"value"+i);
        }
        System.out.println("1秒钟redis写操作:"+i);
        jedis.close();
    }
}

三、spring集成redis数据库操作

  • 需要引入依赖
<dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-redis</artifactId>
            <version>2.5.0</version>
        </dependency>

        <!--json字符串格式-->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.12.2</version>
        </dependency>


        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.20</version>
        </dependency>
  • 需要开启注解,spring配置类实现:jedis连接池配置、jedis连接工厂、redis公共工具类
@Configuration
public class RedisConfig {
    /**
     * jedis连接池配置
     * @return
     */
    @Bean
    public JedisPoolConfig jedisPoolConfig(){
        JedisPoolConfig poolConfig=new JedisPoolConfig();
        poolConfig.setMaxTotal(100);
        poolConfig.setMaxIdle(10);
        poolConfig.setMinIdle(0);
        return poolConfig;
    }

    /**
     * jedis连接工厂
     * @return
     */
    @Bean
    public JedisConnectionFactory jedisConnectionFactory(){
        return new JedisConnectionFactory(jedisPoolConfig());
    }

    /**
     * redis公共工具类
     * @return
     */
    @Bean
    public RedisTemplate redisTemplate(){
        RedisTemplate redisTemplate=new RedisTemplate();
        redisTemplate.setConnectionFactory(jedisConnectionFactory());
        /**
         * 创建序列化类对象
         */
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        GenericJackson2JsonRedisSerializer jackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer();

        /**
         * 指定redis的键值的序列化方式,解决编码乱码问题
         */
        redisTemplate.setKeySerializer(stringRedisSerializer);
        redisTemplate.setHashKeySerializer(stringRedisSerializer);
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
        return redisTemplate;

    }
    @Bean
    @Primary//同一类型如果出现多个实现默认使用这个对象
    /**
     *  StringRedisTemplate 已经把序列化的编码字符串进行了设置
     */
    public RedisTemplate stringRedisTemplate(){
        StringRedisTemplate stringRedisTemplate = new StringRedisTemplate();
        stringRedisTemplate.setConnectionFactory(jedisConnectionFactory());

        /**
         * 这个是把对象字符串转为Json格式,然后Json再转成Json字符串
         */
        GenericJackson2JsonRedisSerializer jackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer();
        stringRedisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        stringRedisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
        return stringRedisTemplate;
    }

}

  • 向redis中添加字符串类型测试类
public class Test3 {
    public static void main(String[] args) {

        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(RedisConfig.class);
        RedisTemplate template = context.getBean(RedisTemplate.class);

        /**
         * value是String类型的操作方法
         */
        template.opsForValue().set("id","1");
        template.opsForValue().set("name","张三");
        template.opsForValue().set("sex","男",10, TimeUnit.SECONDS);
        template.opsForValue().set("age",20,20,TimeUnit.SECONDS);
        template.opsForValue().set("王五老板","王老五",20,TimeUnit.SECONDS);


        User user=new User(1,"令狐冲",56);
        template.opsForValue().set("人数据",user);
        System.out.println("id="+template.opsForValue().get("id"));
        System.out.println("name="+template.opsForValue().get("name"));
        System.out.println("sex="+template.opsForValue().get("sex"));
        System.out.println("age="+template.opsForValue().get("age"));
        System.out.println("王五老板="+template.opsForValue().get("王五老板"));
        System.out.println("人数据="+template.opsForValue().get("人数据"));
        //template.opsForValue().get("id")

    }
}

  • 向redis中hash的map类型测试类
public class Test4 {
    public static void main(String[] args) {

        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(RedisConfig.class);
        RedisTemplate template = context.getBean(RedisTemplate.class);

        /**
         * 添加元素
         */
        Map map=new HashMap<>();
        map.put("学号1",new User(1,"准哥",24));
        map.put("学号2",new User(2,"超哥",23));
        map.put("学号3",new User(3,"耿哥",23));

        /**
         * 设置多个hashkey
         */
        template.opsForHash().putAll("班级1",map);
        /**
         * 设置单个hashkey
         */
        template.opsForHash().put("班级1","学号4",new User(4,"讴歌",25));

        /**
         * 获取所有的键值对
         */
        Map map1 = template.opsForHash().entries("班级1");
        map1.forEach((k,v)->{
            System.out.println(k+"========="+v);
        });

        /**
         * 获取所有的键
         */
        Set keys = template.opsForHash().keys("班级1");
        keys.forEach(key->{
            System.out.println("key = " + key);
        });

        /**
         * 获取所有的值
         */
        List values = template.opsForHash().values("班级1");
        values.forEach(value->{
            System.out.println("value = " + value);
        });

    }
}

  • 向redis中添加list类型测试类
public class Test5 {
    public static void main(String[] args) {

        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(RedisConfig.class);
        RedisTemplate template = context.getBean(RedisTemplate.class);

        //value是list类型的操作方法
        /**
         * 列表左插入
         */
       List<String> names = new ArrayList<>();
        names.add("斌哥");
        names.add("恒哥");
        names.add("老沈");

        template.opsForList().leftPushAll("names",names);
        template.opsForList().leftPush("names","老王");


        /**
         * 列表右插入
         */
        List<String> names1 = new ArrayList<>();
        names1.add("binge");
        names1.add("hengge");
        names1.add("laosheng");
        template.opsForList().leftPushAll("names",names1);
        template.opsForList().leftPush("names","小兰");

         /**
         * 获取list的值
         */
        System.out.println("元素个数 = " + template.opsForList().size("names"));
        /**
         * 获取所有元素,按照从左到右的顺序输出
         */

        List list = template.opsForList().range("names", 0, -1);
        list.forEach(name-> System.out.println("name = " + name));
        /**
         * 获取指定元素,从左到右,第一个元素序号是0
         */

        System.out.println("元素="+template.opsForList().index("names",1));

        /**
         * list装对象集合
         */
        List<User> users = new ArrayList<>();
        users.add(new User(1,"张三0",22));
        users.add(new User(2,"张三1",22));
        users.add(new User(3,"张三2",22));
        template.opsForList().leftPushAll("users",users);
        template.opsForList().leftPush("users",new User(4,"张三4",25));
        System.out.println("元素个数 = " + template.opsForList().size("users"));
        List list1 = template.opsForList().range("users", 0, -1);
        list.forEach(user-> System.out.println("user = " + user));
        System.out.println("元素="+template.opsForList().index("users",1));
        

    }
}

  • 向redis中添加lSet类型测试类
public class Test6 {
    public static void main(String[] args) {

        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(RedisConfig.class);
        RedisTemplate template = context.getBean(RedisTemplate.class);

        //value是set类型的操作方法

        //添加元素,不应许有重复的元素,重复的元素不会加到集合中set
        template.opsForSet().add("set1","张三","李四","王五","李四");
        //遍历元素
        System.out.println("set1集合的元素个数="+template.opsForSet().size("set1"));

        System.out.println("=============集合所有元素=============");
        Set set1 = template.opsForSet().members("set1");
        set1.forEach(name-> System.out.println("name = " + name));
        System.out.println("==============================");
        /**
         * 随机弹出一个元素
         */
        Object pop = template.opsForSet().pop("set1");
        System.out.println("随机移除的元素 = " + pop);
        // System.out.println();

        template.opsForSet().add("set2","张三","李四","王五","李四","赵恒");
        template.opsForSet().add("set3","张一","朱二","王三","李四","赵六");

        /**
         * 两个集合的交集
         */
        System.out.println("================两个集合的交集====================");
        Set intersect = template.opsForSet().intersect("set2", "set3");

        intersect.forEach(name-> System.out.println("name = " + name));
        /**
         * 两个集合的并集
         */
        System.out.println("================两个集合的并集====================");
        Set union = template.opsForSet().union("set2", "set3");
        union.forEach(name -> System.out.println("name = " + name));


        /**
         * 两个集合的差集,可以解决好友对方没有自己关注过的内容推送到对方进行推送
         */
        System.out.println("================两个集合的差集====================");

        Set difference = template.opsForSet().difference("set3", "set2");
        difference.forEach(name-> System.out.println("name = " + name));

        /**
         * 两个集合的交集
         */
        System.out.println("============两个集合的交集元素存入到set集合中======================");

        Long store = template.opsForSet().intersectAndStore("set2", "set3", "set");
        System.out.println("store = " + store);

        /**
         * 两个集合的并集
         */
        System.out.println("============两个集合的交集元素存入到set4集合中======================");

        Long store1 = template.opsForSet().unionAndStore("set2", "set3", "set4");
        System.out.println("store1 = " + store1);
        /**
         * 两个集合的差集
         */
        System.out.println("============两个集合的差集元素存入到set5集合中======================");

        Long store2 = template.opsForSet().differenceAndStore("set2", "set3", "set5");
        System.out.println("store2 = " + store2);

    }

}

  • 如果是利用RedisTemplate工具类中的子类StringRedisTemplate的话,就需要注意对象类型数据在转换时会出现错误,无法把对象转成字符串,需要借助Json格式过渡,再转成Json字符串格式
    配置类代码如下
@Bean
    @Primary//同一类型如果出现多个实现默认使用这个对象
    /**
     *  StringRedisTemplate 已经把序列化的编码字符串进行了设置
     */
    public RedisTemplate stringRedisTemplate(){
        StringRedisTemplate stringRedisTemplate = new StringRedisTemplate();
        stringRedisTemplate.setConnectionFactory(jedisConnectionFactory());

        /**
         * 这个是把对象字符串转为Json格式,然后Json再转成Json字符串
         */
        GenericJackson2JsonRedisSerializer jackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer();
        stringRedisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        stringRedisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
        return stringRedisTemplate;
    }

测试类代码如下

public class Test7 {
    public static void main(String[] args) {

        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(RedisConfig.class);
        RedisTemplate template = context.getBean(RedisTemplate.class);

        /**
         * value是String类型的操作方法
         */
        template.opsForValue().set("id","1");
        template.opsForValue().set("name","张三");
       /* template.opsForValue().set("sex","男",10, TimeUnit.SECONDS);
        template.opsForValue().set("age","20",20,TimeUnit.SECONDS);
        template.opsForValue().set("王五老板","王老五",20,TimeUnit.SECONDS);
*/
        template.opsForValue().set("sex","男");
        template.opsForValue().set("age","20");
        template.opsForValue().set("王五老板","王老五");

        User user=new User(1,"令狐冲",56);
        template.opsForValue().set("人数据",user);


        System.out.println("id="+template.opsForValue().get("id"));
        System.out.println("name="+template.opsForValue().get("name"));
        System.out.println("sex="+template.opsForValue().get("sex"));
        System.out.println("age="+template.opsForValue().get("age"));
        System.out.println("王五老板="+template.opsForValue().get("王五老板"));
        System.out.println("人数据="+template.opsForValue().get("人数据"));
        //template.opsForValue().get("id")

    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值