springboot 中的redis配置(Jedis )(非集群)

  1. pom.xml

       <!--redis 相关jar包-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
    
  2. application.properties

     spring.redis.host= 127.0.0.1
     spring.redis.port= 6379
    
  3. config

    	import org.slf4j.Logger;
    	import org.slf4j.LoggerFactory;
    	import org.springframework.beans.factory.annotation.Value;
    	import org.springframework.context.annotation.Bean;
    	import org.springframework.context.annotation.Configuration;
    	import org.springframework.context.annotation.PropertySource;
    	import redis.clients.jedis.JedisPool;
    	import redis.clients.jedis.JedisPoolConfig;
    	
    	@Configuration
    	@PropertySource(value="classpath:bootstrap.properties")
    	public class RedisConfig {
    
        private Logger log = (Logger) LoggerFactory.getLogger(RedisConfig.class);
    
        @Value("${spring.redis.host}")
        private String host;
    
        @Value("${spring.redis.port}")
        private int port;
    
        @Bean
        public JedisPool getJedisPool(){
            log.info("==>初始化jedis连接池");
            JedisPoolConfig config = new JedisPoolConfig();
            JedisPool pool = new JedisPool(config, host, port);
            return pool;
        }
    }
    
  4. 在 要用的类中注入:

     	 @Autowired
         private JedisPool jedisPool;
    
  5. 方法中使用:

      Jedis redis = jedisPool.getResource();
    
    	redis.set("key值","value");
        redis.lpush("key值","value");
        redis.expire("key值",时间:秒);
    
     //llen  的方法  取出list长度
     redis.llen(phoneNumber + format);
    

猜你喜欢

转载自blog.csdn.net/cxy_chh/article/details/91490809