本demo基于springboot2.1.3,maven依赖项如下:

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.9.0</version>
        </dependency>
        <!-- swagger2-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>${swagger.version}</version>
        </dependency>

        <!-- swagger2-UI-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>${swagger.version}</version>
        </dependency>
        <!-- lombok 简化代码,比如log和get set-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

application配置:

spring:
  application:
    name: springbootdemo
  redis:
    # Redis数据库索引(默认为0)
    database: 0
    # Redis服务器地址
    host: 127.0.0.1
    # Redis服务器连接端口
    port: 6379
    jedis:
      pool:
        # 连接池中的最小空闲连接
        min-idle: 0
        # 连接池中的最大空闲连接
        max-idle: 10
        # 连接池最大连接数(使用负值表示没有限制)
        max-active: 10
        # 连接池最大阻塞等待时间(使用负值表示没有限制)
        max-wait: -1
        testOnBorrow: true
        testWhileIdle: true
        minEvictableIdleTimeMills: 60000
        timeBetweenEvictionRunsMillis: 30000
        numTestsPerEvictionRun: -1
    # 连接超时时间(毫秒)
    timeout: 5000
RedisConfig相关代码:

    @Bean
    public JedisPoolConfig jedisPoolConfig(){
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();

        jedisPoolConfig.setMaxIdle(maxIdle);
        jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);
        jedisPoolConfig.setTestWhileIdle(testWhileIdle);
        jedisPoolConfig.setTestOnBorrow(testOnBorrow);
        jedisPoolConfig.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMills);
        jedisPoolConfig.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
        jedisPoolConfig.setNumTestsPerEvictionRun(numTestsPerEvictionRun);
        jedisPoolConfig.setTestOnCreate(true);
        jedisPoolConfig.setTestOnReturn(true);
        return jedisPoolConfig;
    }

    @Bean
    public RedisConnectionFactory redisConnectionFactory(JedisPoolConfig jedisPoolConfig) {
        RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
        //设置redis服务器的host或者ip地址
        redisStandaloneConfiguration.setHostName(host);
        redisStandaloneConfiguration.setPort(port);
        //获得默认的连接池构造
        //这里需要注意的是,edisConnectionFactoryJ对于Standalone模式的没有(RedisStandaloneConfiguration,JedisPoolConfig)的构造函数,对此
        //我们用JedisClientConfiguration接口的builder方法实例化一个构造器,还得类型转换
        JedisClientConfiguration.JedisPoolingClientConfigurationBuilder jpcf = (JedisClientConfiguration.JedisPoolingClientConfigurationBuilder) JedisClientConfiguration.builder();
        //修改我们的连接池配置
        jpcf.poolConfig(jedisPoolConfig);
        //通过构造器来构造jedis客户端配置
        JedisClientConfiguration jedisClientConfiguration = jpcf.build();

        return new JedisConnectionFactory(redisStandaloneConfiguration, jedisClientConfiguration);
    }

    /**
     * @Description: 防止redis入库序列化乱码的问题
     * @return     返回类型
     * @date 2018/4/12 10:54
    */
    @Bean
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){
        RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<Object, Object>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        redisTemplate.setKeySerializer(new StringRedisSerializer());//key序列化
        redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer(Object.class));  //value序列化
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(new Jackson2JsonRedisSerializer(Object.class));
        redisTemplate.setDefaultSerializer(new Jackson2JsonRedisSerializer(Object.class));

        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }

redis工具类:


@Component
public class RedisUtil {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * set集合获取
     * @param key
     * @return
     */
    public Set<Object> getMembers(String key){
        SetOperations<String, Object> set = redisTemplate.opsForSet();
        return set.members(key);
    }

    /**
     * 集合set中是否存在目标对象
     * @param key
     * @param value
     * @return
     */
    public Boolean isMember(String key, Object value){
        return redisTemplate.opsForSet().isMember(key, value);
    }

    public void addMember(String key, Object value) {
        redisTemplate.opsForSet().add(key, value);
    }

    public void delMember(String key, Object value) {
        redisTemplate.opsForSet().remove(key, value);
    }

    public Long getExpire(String key) {
        return redisTemplate.getExpire(key,TimeUnit.MILLISECONDS);
    }

    public void setExpire(String key, Integer time) {
        redisTemplate.expire(key, time, TimeUnit.MILLISECONDS);
    }

    public void setValue(String key, Object value) {
        redisTemplate.opsForValue().set(key, value);
    }

    public Object getValue(String key) {
        return redisTemplate.opsForValue().get(key);
    }

    public void delValue(String key) {
        redisTemplate.opsForValue().getOperations().delete(key);
    }
}

测试用的controller:

@Slf4j
@RestController
@RequestMapping("redis")
public class RedisDemoController {
    @Autowired
    private RedisUtil redisUtil;

    @RequestMapping(value = "/setRedis", method = RequestMethod.POST)
    public String setRedis(String value) {
        String result;
        try {
            redisUtil.setValue("redis_key", value);
            result = "redis设置成功";
        } catch (Exception e) {
            result = "redis设置失败:" + e.getMessage();
        }
        return result;
    }


    @RequestMapping(value = "/getRedis", method = RequestMethod.GET)
    public String getRedis() {
        String result;
        try {
            String value = (String) redisUtil.getValue("redis_key");
            result = "redis读取成功:" + value;
        } catch (Exception e) {
            result = "redis读取失败:" + e.getMessage();
        }
        return result;
    }
}

有什么不清楚的可以参考github上的demo的singleRedis分支:

https://github.com/whol/springbootdemo

 

最后修改于 2019-03-04 16:37:25
如果觉得我的文章对你有用,请随意赞赏
扫一扫支付
上一篇