Jedis connect an external Redis

Jedis connect an external Redis

1. In the redis server open port 6379 by default, if there is pagoda panel is also required to release the 6379 port pagoda
2. Modify redis.conf

Comment out the binding IP 127.0.0.1

# bind 127.0.0.1

 

Set password redis

    requirepass 123456

 

3. Project import dependence
    <dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    </dependency>

 

4.applicaiton.yml add configuration (password to add double quotes)
    spring:
    redis:
    host: 120.57.56.220
    port: 6379
    password: "123456"
    jedis:
    pool:
    max-active: 8
    max-idle: 8
    min-idle: 2
    timeout: 2000

 

5. Add configuration class
    @Configuration
    public class JedisConfig {
    private Logger logger = LoggerFactory.getLogger(JedisConfig.class);
    @Value("${spring.redis.host}")
    private String host;
    @Value("${spring.redis.port}")
    private int port;
    @Value("${spring.redis.password}")
    private String password;
    @Value("${spring.redis.timeout}")
    private int timeout;
    @Value("${spring.redis.jedis.pool.max-active}")
    private int maxActive;
    @Value("${spring.redis.jedis.pool.max-idle}")
    private int maxIdle;
    @Value("${spring.redis.jedis.pool.min-idle}")
    private int minIdle;
    @Bean
    public JedisPool jedisPool(){
    JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
    jedisPoolConfig.setMaxIdle(maxIdle);
    jedisPoolConfig.setMinIdle(minIdle);
    jedisPoolConfig.setMaxTotal(maxActive);
    JedisPool jedisPool = new JedisPool(jedisPoolConfig,host,port,timeout,password);
    logger.info("JedisPool连接成功: "+host+"/"+port );
    return jedisPool;
    }
    }

 

6. Get the Jedis call the method by JedisPool
    @Autowired
    private JedisPool jedisPool;
    public String getValue(String key) {
    String value = null;
    Jedis jedis = jedisPool.getResource();
    if (jedis.exists(key)){
    log.info("通过Redis取值");
    value = jedis.get(key);
    }else {
    log.info("通过Mysql取值");
    value = "value";
    jedis.set(key,value);
    }
    jedis.close();
    return value;
    }

 

My personal blog www.gofy.top

Guess you like

Origin www.cnblogs.com/gaofei200/p/12642118.html