(2) SpringBoot 2.X 集成Redis

1. 阿里云服务器(centos7.3)上安装Redis

2. Reids 的SpringBoot 配置

1. pom.xml 添加依赖Redis和Fastjson依赖
    <dependency>
      <groupId>redis.clients</groupId>
      <artifactId>jedis</artifactId>
    </dependency>

    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>1.2.38</version>
    </dependency>
2. application.properties 添加配置
#Redis
redis.host=47.103.118.58
redis.port=6379
redis.password=
redis.timeout=100 
redis.poolMaxTotal=1000
redis.poolMaxIdle=500
redis.poolMaxWait=500

3.代码测试

1. RedisConfig获取配置
  • @ConfigurationProperties(prefix=“redis”)指定配置文件里面前缀为"redis"的配置项,与配置项里面的属性对应起来。
@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;
    public String getHost() {
        return host;
    }
    public void setHost(String host) {
        this.host = host;
    }
    public int getPort() {
        return port;
    }
    public void setPort(int port) {
        this.port = port;
    }
    public int getTimeout() {
        return timeout;
    }
    public void setTimeout(int timeout) {
        this.timeout = timeout;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public int getPoolMaxTotal() {
        return poolMaxTotal;
    }
    public void setPoolMaxTotal(int poolMaxTotal) {
        this.poolMaxTotal = poolMaxTotal;
    }
    public int getPoolMaxIdle() {
        return poolMaxIdle;
    }
    public void setPoolMaxIdle(int poolMaxIdle) {
        this.poolMaxIdle = poolMaxIdle;
    }
    public int getPoolMaxWait() {
        return poolMaxWait;
    }
    public void setPoolMaxWait(int poolMaxWait) {
        this.poolMaxWait = poolMaxWait;
    }
}
2. JedisFactory
  • 再在redis包中创建RedisPoolFactory类,RedisPoolFactory 通过配置文件,生成Jedis连接池(配置),方便在RedisService中调用
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);
        /**
          *database:0;redis默认支持16个库,不指定默认用0号库
          */
        return jp;
    }

}
3. RedisService
  • 创建RedisService类来提供所有关于redis的服务方法
@Service
public class RedisService {
   @Autowired
   JedisPool jedisPool;
   /**
    * 获取当个对象
    * */
   public <T> T get(KeyPrefix prefix, String key,  Class<T> clazz) {
       Jedis jedis = null;
       try {
           jedis =  jedisPool.getResource();
           //生成真正的key
           String realKey  = prefix.getPrefix() + key;
           String  str = jedis.get(realKey);
           T t =  stringToBean(str, clazz);
           return t;
       }finally {
           returnToPool(jedis);
       }
   }

   /**
    * 设置对象
    * */
   public <T> boolean set(KeyPrefix prefix, String key,  T value) {
       Jedis jedis = null;
       try {
           jedis =  jedisPool.getResource();
           String str = beanToString(value);
           if(str == null || str.length() <= 0) {
               return false;
           }
           //生成真正的key
           String realKey  = prefix.getPrefix() + key;
           int seconds =  prefix.expireSeconds();
           if(seconds <= 0) {
               jedis.set(realKey, str);
           }else {
               jedis.setex(realKey, seconds, str);
           }
           return true;
       }finally {
           returnToPool(jedis);
       }
   }

   public static <T> String beanToString(T value) {
       if(value == null) {
           return null;
       }
       Class<?> clazz = value.getClass();
       if(clazz == int.class || clazz == Integer.class) {
           return ""+value;
       }else if(clazz == String.class) {
           return (String)value;
       }else if(clazz == long.class || clazz == Long.class) {
           return ""+value;
       }else {
           return JSON.toJSONString(value);
       }
   }
   public static <T> T stringToBean(String str, Class<T> clazz) {
       if(str == null || str.length() <= 0 || clazz == null || str == "") {
           return null;
       }
       if(clazz == int.class || clazz == Integer.class) {
           return (T)Integer.valueOf(str);
       }else if(clazz == String.class) {
           return (T)str;
       }else if(clazz == long.class || clazz == Long.class) {
           return  (T)Long.valueOf(str);
       }else {
           return JSON.toJavaObject(JSON.parseObject(str), clazz);
       }
   }
   private void returnToPool(Jedis jedis) {
       if(jedis != null) {
           jedis.close();
       }
   }

}
4. Controller测试
@Controller
@RequestMapping("/demo")
public class sampleController {
    @Autowired
    RedisService redisService;
    @RequestMapping("/redis/get")
    @ResponseBody
    public Result<User> redisGet() {
        User user  = redisService.get(UserKey.getById, ""+1, User.class);
        return Result.success(user);
    }

    @RequestMapping("/redis/set")
    @ResponseBody
    public Result<Boolean> redisSet() {
        User user  = new User();
        user.setId(1);
        user.setName("1111");
        redisService.set(UserKey.getById, ""+1, user);//UserKey:id1
        return Result.success(true);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值