zoukankan      html  css  js  c++  java
  • springboot与jedis的整合

    1、创建SpringBoot工程

    使用idea自带的Spring Initializr创建一个基本的SpringBoot工程。

    2、修改POM文件

    工程创建成功后,修改pom文件,添加所需的jar包

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
    
    <dependency>
        <groupId>redis.clients</groupId>
        <artifactId>jedis</artifactId>
        <version>3.1.0</version>
    </dependency>
    
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.8</version>
        <scope>provided</scope>
    </dependency>
    View Code

    3、添加所需配置

    application.properties配置

    # Redis服务器地址
    redis.host=127.0.0.1
    # Redis服务器连接端口
    redis.port=6379
    # Redis服务器连接密码(默认为空)
    redis.password=null
    redis.timeout=30000
    # 连接池最大连接数(使用负值表示没有限制)
    redis.maxTotal=30
    # 连接池中的最大空闲连接
    redis.maxIdle=10
    redis.numTestsPerEvictionRun=1024
    redis.timeBetweenEvictionRunsMillis=30000
    redis.minEvictableIdleTimeMillis=1800000
    redis.softMinEvictableIdleTimeMillis=10000
    # 连接池最大阻塞等待时间(使用负值表示没有限制)
    redis.maxWaitMillis=1500
    redis.testOnBorrow=true
    redis.testWhileIdle=true
    redis.blockWhenExhausted=false
    redis.JmxEnabled=true
    View Code

    RedisConfig配置文件

    @Configuration
    @PropertySource("classpath:application.properties")
    public class RedisConfig {
        @Value("${redis.host}")
        private String host;
    
        @Value("${redis.port}")
        private int port;
    
        @Value("${redis.timeout}")
        private int timeout;
    
        @Value("${redis.maxIdle}")
        private int maxIdle;
    
        @Value("${redis.maxWaitMillis}")
        private int maxWaitMillis;
    
        @Value("${redis.blockWhenExhausted}")
        private Boolean blockWhenExhausted;
    
        @Value("${redis.JmxEnabled}")
        private Boolean JmxEnabled;
    
        @Bean
        public JedisPool jedisPoolFactory() {
            JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
            jedisPoolConfig.setMaxIdle(maxIdle);
            jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);
            // 连接耗尽时是否阻塞, false报异常,true阻塞直到超时, 默认true
            jedisPoolConfig.setBlockWhenExhausted(blockWhenExhausted);
            // 是否启用pool的jmx管理功能, 默认true
            jedisPoolConfig.setJmxEnabled(JmxEnabled);
            JedisPool jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout);
            return jedisPool;
        }
    }
    View Code

    4、编写代码

    编写RedisUtil工具类

    @Component
    public class RedisUtil {
    
        @Autowired
        private JedisPool jedisPool;
    
        /**
         * 向Redis中存值,永久有效
         */
        public String set(String key, String value) {
            Jedis jedis = null;
            try {
                jedis = jedisPool.getResource();
                return jedis.set(key, value);
            } catch (Exception e) {
                return "0";
            } finally {
                jedis.close();
            }
        }
    
        /**
         * 根据传入Key获取指定Value
         */
        public String get(String key) {
            Jedis jedis = null;
            String value;
            try {
                jedis = jedisPool.getResource();
                value = jedis.get(key);
            } catch (Exception e) {
                return "0";
            } finally {
                jedis.close();
            }
            return value;
        }
    
        /**
         * 校验Key值是否存在
         */
        public Boolean exists(String key) {
            Jedis jedis = null;
            try {
                jedis = jedisPool.getResource();
                return jedis.exists(key);
            } catch (Exception e) {
                return false;
            } finally {
                jedis.close();
            }
        }
    
        /**
         * 删除指定Key-Value
         */
        public Long del(String key) {
            Jedis jedis = null;
            try {
                jedis = jedisPool.getResource();
                return jedis.del(key);
            } catch (Exception e) {
                return 0L;
            } finally {
                jedis.close();
            }
        }
    
        /**
         * 分布式锁
         * @param key
         * @param value
         * @param time 锁的超时时间,单位:秒
         *
         * @return 获取锁成功返回"OK",失败返回null
         */
        public String getDistributedLock(String key,String value,int time){
            Jedis jedis = null;
            String ret = "";
            try {
                jedis = jedisPool.getResource();
    
                ret = jedis.set(key, value, new SetParams().nx().ex(time));
                return ret;
            } catch (Exception e) {
                return null;
            } finally {
                jedis.close();
            }
        }
    
    
    }
    View Code

    编写Controller,便于从浏览器进行测试

    @RestController
    @Slf4j
    public class RedisController {
    
        @Autowired
        private RedisUtil redisUtil;
    
        @RequestMapping("/testDistributedLock")
        public String testSetIfNotExists(@RequestParam("name") String name,
                                         @RequestParam("value") int age){
            log.info("******testSetIfNotExists******");
    
            int time = 10;//超时时间写死为10秒
            String ageStr = String.valueOf(age);
            String s = redisUtil.getDistributedLock(name, ageStr, time);
    
            log.info("******s是否为null:" + (s == null));
            log.info("******s=" + s);
    
            return s;
        }
    }
    View Code

    5、启动测试

    启动SpringBoot工程,打开浏览器进行测试

    http://localhost:8080/testDistributedLock?name=jack&value=25

    浏览器成功响应OK

  • 相关阅读:
    nginx公网IP无法访问浏览器
    Internet接入方式
    Adobe Photoshop Lightroom 5.3和序列号
    getopt
    printf
    scanf
    cycling -avoid the vicious cycle
    ACE handle_timeout 事件重入
    Linux查看程序端口占用
    The GNU C Library
  • 原文地址:https://www.cnblogs.com/beanbag/p/13081444.html
Copyright © 2011-2022 走看看