Jedis连接外部Redis

Jedis连接外部Redis

1.在服务器开放端口redis默认6379,如果有宝塔面板则还需要在宝塔放行6379端口
2.修改redis.conf

注释掉 绑定IP 127.0.0.1

# bind 127.0.0.1

 

设置redis密码

    requirepass 123456

 

3.项目导入依赖
    <dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    </dependency>

 

4.applicaiton.yml添加配置(密码要加双引号)
    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.添加配置类
    @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.通过JedisPool获取Jedis调用方法
    @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;
    }

 

我的个人博客 www.gofy.top

posted @ 2020-04-06 14:53  小高飞  阅读(238)  评论(0编辑  收藏  举报