• Springboot集成整合Redis-单机版(4)


    【前言】记录整理springboot集成Redis代码。单机版,哨兵集群,cluster集群,完整代码已上传github

    集成单机版Redis

    1.核心maven依赖

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
    <dependency>
        <groupId>redis.clients</groupId>
        <artifactId>jedis</artifactId>
    </dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    2.配置文件application.yml

    spring:
      redis:
        database: 0
        host: 172.28.13.140
        port: 6379
        password: China1234
        timeout: 10000
        jedis:
          pool:
            max-active: 500
            min-idle: 5
            max-idle: 50
            max-wait: 60000
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    3.工具类

    3.1 采用JedisPool(推荐)
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import redis.clients.jedis.Jedis;
    import redis.clients.jedis.JedisPool;
    import redis.clients.jedis.JedisPoolConfig;
    
    /**
     * @description:
     * @author: uwank171
     * @date: 2022/9/1 13:17
     */
    @Configuration
    public class JedisConfig {
    
        /**配置文件中部分参数没有加载进去*/
        @Value("${spring.redis.host}")
        private String host;
        @Value("${spring.redis.port}")
        private int port;
        @Value("${spring.redis.database}")
        private int database;
        @Value("${spring.redis.password}")
        private String password;
        @Value("${spring.redis.timeout}")
        private int timeout;
        @Value("${spring.redis.jedis.pool.max-active}")
        private int maxTotal;
        @Value("${spring.redis.jedis.pool.min-idle}")
        private int minIdle;
        @Value("${spring.redis.jedis.pool.max-idle}")
        private int maxIdle;
        @Value("${spring.redis.jedis.pool.max-wait}")
        private long maxWaitMillis;
    
    
        private static JedisPool jedisPool = null;
    
        public Jedis getJedis() {
            if (jedisPool == null) {
                jedisPool();
            }
            if (jedisPool != null) {
                return jedisPool.getResource();
            }
            return null;
        }
    
        public void closeJedis(Jedis jedis) {
            try {
                if (jedis != null) {
                    jedis.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        @Bean("jedisPool")
        public JedisPool jedisPool() {
            if (jedisPool == null) {
                JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
                jedisPoolConfig.setMinIdle(minIdle);
                jedisPoolConfig.setMaxIdle(maxTotal);
                jedisPoolConfig.setMaxTotal(maxTotal);
                jedisPoolConfig.setBlockWhenExhausted(true);
                jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);
                jedisPoolConfig.setTestOnBorrow(true);
                jedisPoolConfig.setTestOnReturn(true);
                jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout, password, database);
            }
            return jedisPool;
        }
    }
    
    /** JedisUtil类 ,可以自定义添加其它方法*/
    import com.redmaple.common.config.JedisConfig;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Component;
    import redis.clients.jedis.Jedis;
    
    /**
     * @description: 再次封装的目的是为了关闭jedis连接,释放资源。
     * 因为直接使用 Jedis jedis = jedisConfig.getJedis() 操作,在代码中容易忘记 close,且比较麻烦。
     * @author: uwank171
     * @date: 2022/9/1 13:43
     */
    @Component
    public class JedisUtil {
    
        @Autowired
        private JedisConfig jedisConfig;
    
        /**
         * 判断是否存在key
         * @param key
         * @param timeoutSeconds
         * @return
         */
        public boolean expire(String key, int timeoutSeconds) {
            Jedis jedis = jedisConfig.getJedis();
            try {
                jedis.expire(key, timeoutSeconds);
                return true;
            } catch (Exception e) {
                // 打印日志的包没有引入
                //lo1g.error(">>>>> JedisUtils error " + e);
                System.err.println(">>>>> JedisUtils error " + e);
                return false;
            } finally {
                jedisConfig.closeJedis(jedis);
            }
        }
    
        /**
         * 存储数据
         * @param key
         * @param value
         * @return
         */
        public String set(String key, String value) {
            Jedis jedis = jedisConfig.getJedis();
            try {
                return jedis.set(key, value);
            } catch (Exception e) {
                System.err.println(">>>>> JedisUtils error " + e);
                return null;
            } finally {
                jedisConfig.closeJedis(jedis);
            }
        }
    
        /**
         * 获取数据
         * @param key
         * @return
         */
        public String get(String key) {
            Jedis jedis = jedisConfig.getJedis();
            try {
                return jedis.get(key);
            } catch (Exception e) {
                System.err.println(">>>>> JedisUtils error " + e);
                return null;
            } finally {
                jedisConfig.closeJedis(jedis);
            }
        }
    
        /**
         * 删除数据
         * @param key
         * @return
         */
        public boolean del(String key) {
            Jedis jedis = jedisConfig.getJedis();
            try {
                jedis.del(key);
                return true;
            } catch (Exception e) {
                System.err.println(">>>>> JedisUtils error " + e);
                return false;
            } finally {
                jedisConfig.closeJedis(jedis);
            }
        }
    
        /**
         * 判断是否存在key
         * @param key
         * @return
         */
        public boolean exists(String key) {
            Jedis jedis = jedisConfig.getJedis();
            try {
                return jedis.exists(key);
            } catch (Exception e) {
                System.err.println(">>>>> JedisUtils error " + e);
                return false;
            } finally {
                jedisConfig.closeJedis(jedis);
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    3.2 直接new Jedis()

    这么操作确实很简易,但是需要手动关闭close,使用过多的会比较繁琐

    import redis.clients.jedis.Jedis;
    
    /**
     * @description: 简易版,可以按需求自己修改
     * @author: uwank171
     * @date: 2022/9/1 13:43
     */
    public class JedisUtil2 {
    
        private static String host = "172.28.13.140";
        private static int port = 6379;
    
        public static void main(String[] args) {
            Jedis jedis = null;
            try {
                jedis = new Jedis(host, port);
                String key = "redis_key1";
                String value = "redis_1001";
                // 存入数据
                jedis.set(key, value);
                // 获取数据
                System.out.println(jedis.get(key));
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (jedis != null) {
                    jedis.close();
                }
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    3.3 RedisTemplate 序列化方式
    /**
     * @description: 注意需要序列化的对象一定要实现Serializable接口
     * @author: uwank171
     * @date: 2022/9/1 13:43
     */
    @Component
    public class JedisUtil3 {
        @Resource
        private RedisTemplate<String, Object> redisTemplate;
    
        public void setObject(String key, Object object) {
            redisTemplate.opsForValue().set(key, object);
        }
    
        public Object getObjet(String key) {
            return redisTemplate.opsForValue().get(key);
        }
    }
    
    /** 注意需要序列化的对象一定要实现Serializable接口 */
    @Data
    public class UserEntity implements Serializable {
        private Long userId;
        private String userName;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25

    4.测试Controller

    @RestController
    public class RedisStandloneController {
    
        @Autowired
        private JedisUtil jedisUtil;
    
        @GetMapping("/setKey")
        public String setKey(String key, String value) {
            jedisUtil.set(key, value);
            return "===setKey完成===key:" + key + " value:" + value;
        }
    
        @GetMapping("/getKey")
        public String getKey(String key) {
            String value = jedisUtil.get(key);
            return "===getKey完成===key:" + key + " value:" + value;
        }
    
    
    //=========================================================================
    
        @Autowired
        private JedisUtil3 jedisUtil3;
    
        @GetMapping("/setObj")
        public String setObj(String key, String value) {
            jedisUtil3.setObject(key, value);
            return "===setKey完成===key:" + key + " value:" + value;
        }
    
        @GetMapping("/getObj")
        public String getObj(String key) {
            String value = (String) jedisUtil3.getObjet(key);
            return "===getKey完成===key:" + key + " value:" + value;
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35

    以上就是整合单记版的redis,最后的RedisTemplate方法还可以在项目启动时重新修改序列化在注入到容器中更方便点,后续再更新。

    如果该文章能够帮助到你,希望麻烦点赞收藏下,谢谢。

  • 相关阅读:
    Python批量将Photoshop文件保存为图片
    Windows server 2016——权限管理与数据恢复
    运维的利器–监控–zabbix–第二步:建设–部署zabbix agent--windows server系统
    入门【网络安全/黑客】启蒙教程
    2022年9月总结
    C++ 网络编程 建立简单的TCP通信
    pytorch入门1
    Python基于OpenCV&YOLO台球击球路线规划系统(源码&部署教程)
    指数族分布(2):矩母函数、累积量生成函数
    使用bsdconfig配置CBSD NAT
  • 原文地址:https://blog.csdn.net/qq_34846877/article/details/126640981