maven springboot Redis环境搭建

一、添加pom.xml依赖

  • 添加Jedis依赖
  • 添加Fastjson依赖
  • 添加读取springboot配置文件的依赖,后面读取application.properties里面设置的redis信息会用到
<dependency>
 	<groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.62</version>
</dependency>
<dependency>
	<groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>

二、在application.properties中添加redis需要的配置

#redis
redis.host=ip地址
redis.port=6379
redis.timeout=3
redis.password=123456
redis.poolMaxTotal=10
redis.poolMaxIdle=10
redis.poolMaxWait=3

三、获取Jedis对象(相当于redis客户端,通过这个对象可以操控你的服务器redis)

分为以下几个步骤:

  1. 将application.properties里面redis配置信息封装到RedisConfig对象中
  2. 通过RedisConfig和JedisPoolConfig创建JedisPool
  3. 通过jedisPool.getResource()获取Jedis
  4. 通过Jedis操作Redis
1.RedisConfig
@Component
@ConfigurationProperties(prefix = "redis")
public class RedisConfig {
    private String host;
    private int port;
    private int timeout;
    private String password;
    private int poolMaxTotal;
    private int poolMaxIdle;
    private int poolMaxWait;
}
2.RedisPoolFactory
@Service
public class RedisPoolFactory {

    @Autowired
    RedisConfig redisConfig;

    @Bean
    public JedisPool JedisPoolFactory() {
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxIdle(redisConfig.getPoolMaxIdle());
        poolConfig.setMaxTotal(redisConfig.getPoolMaxTotal());
        poolConfig.setMaxWaitMillis(redisConfig.getPoolMaxWait() * 1000);
        JedisPool jp = new JedisPool(poolConfig, redisConfig.getHost(), redisConfig.getPort(),
                redisConfig.getTimeout()*1000, redisConfig.getPassword(), 0);
        return jp;
    }
}
3/4 获取Jedis并操作Redis
public <T> T get(String key, Class<T> clazz) {
    Jedis jedis = null;
    try {
        jedis = jedisPool.getResource();
        String str = jedis.get(realKey);
        T t = stringToBean(str, clazz);
        return t;
    } finally {
        returnToPool(jedis);
    }
}

直接用key当作redis<key, value>中的key的话,冲突很严重,会造成一定问题,最好自己对key进行一些特殊处理。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值