1. 程式人生 > >springboot redis配置

springboot redis配置

1、引入maven依賴

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

 

2、redis連線配置

spring:
  redis:
    host: 10.220.1.41
    port: 6379
    timeout: 10000
    password:
    jedis:
      pool:
        #最大連線數
        max-active: 8
        #最大阻塞等待時間(負數表示沒限制)
        max-wait: -1ms
        #最大空閒
        max-idle: 8
        #最小空閒
        min-idle: 0

 

3、redisTemplate配置,其實springboot2不配置也是可以直接使用的,但是我們可以指定一下key,value序列化的方式,如下

@Configuration
public class RedisConfiguration extends CachingConfigurerSupport {

    @Bean
    @Override
    public KeyGenerator keyGenerator() {
        return (target, method, params) -> {
            StringBuilder sb 
= new StringBuilder(); sb.append(target.getClass().getName()); sb.append(method.getName()); for (Object obj : params) { sb.append(obj.toString()); } return sb.toString(); }; } @Bean public CacheManager cacheManager(RedisConnectionFactory connectionFactory) {
return RedisCacheManager.builder(connectionFactory).build(); } @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){ RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(redisConnectionFactory); redisTemplate.setKeySerializer(new StringRedisSerializer()); redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer()); redisTemplate.setHashKeySerializer(new StringRedisSerializer()); redisTemplate.setHashValueSerializer(new JdkSerializationRedisSerializer()); redisTemplate.afterPropertiesSet(); return redisTemplate; } }

4、KeyPrefix類定義,方便管理key的字首與超時時間(防止key管理混亂,出現後面的key覆蓋前面的key的情況)

public class KeyPrefix {
    private String prefix;
    private Long timeout;//0或負數或空是表示永不過期

    public KeyPrefix(String prefix, Long timeout) {
        this.prefix = prefix;
        this.timeout = timeout;
    }

  //所有的key字首統一在這了定義,方便管理
public static KeyPrefix LOGIN_USER_KP = new KeyPrefix("login_user_",10000L); public String getPrefix() { return prefix; } public void setPrefix(String prefix) { this.prefix = prefix; } public Long getTimeout() { return timeout; } public void setTimeout(Long timeout) { this.timeout = timeout; } }

 

5、寫一個通用的服務類,鍵值對的插入和查詢等

@Component
public class RedisService<HK, V> {

    private RedisTemplate<String, V> redisTemplate;
    private HashOperations<String, HK, V> hashOperations;
    private ListOperations<String, V> listOperations;
    private ZSetOperations<String, V> zSetOperations;
    private SetOperations<String, V> setOperations;
    private ValueOperations<String, V> valueOperations;

    @Autowired
    public RedisService(RedisTemplate<String, V> redisTemplate) {
        this.redisTemplate = redisTemplate;
        this.hashOperations = redisTemplate.opsForHash();
        this.listOperations = redisTemplate.opsForList();
        this.zSetOperations = redisTemplate.opsForZSet();
        this.setOperations = redisTemplate.opsForSet();
        this.valueOperations = redisTemplate.opsForValue();
    }


    public void hashPut(String key, HK hashKey, V value) {
        hashOperations.put(key, hashKey, value);
    }

    public Map<HK, V> hashFindAll(String key) {
        return hashOperations.entries(key);
    }

    public V hashGet(String key, HK hashKey) {
        return hashOperations.get(key, hashKey);
    }

    public void hashRemove(String key, HK hashKey) {
        hashOperations.delete(key, hashKey);
    }

    public Long listPush(String key, V value) {
        return listOperations.rightPush(key, value);
    }

    public Long listUnshift(String key, V value) {
        return listOperations.leftPush(key, value);
    }

    public List<V> listFindAll(String key) {
        if (!redisTemplate.hasKey(key)) {
            return null;
        }
        return listOperations.range(key, 0, listOperations.size(key));
    }

    public V listLPop(String key) {
        return listOperations.leftPop(key);
    }

    public void setValue(String key, V value) {
        valueOperations.set(key, value);
    }

    public void setValue(KeyPrefix kp, String key, V value) {
        Long timeout = kp .getTimeout();
        if(timeout == null || timeout <= 0){
            this.setValue(kp.getPrefix() + key, value);
        }else{
            this.setValue(kp.getPrefix() + key, value, kp.getTimeout());
        }
    }

    public void setValue(String key, V value, long timeout) {
        valueOperations.set(key, value, timeout, TimeUnit.MILLISECONDS);
    }


    public V getValue(String key) {
        return valueOperations.get(key);
    }

    public void remove(String key) {
        redisTemplate.delete(key);
    }

    public boolean expire(String key, long timeout, TimeUnit timeUnit) {
        return redisTemplate.expire(key, timeout, timeUnit);
    }

}

 

6、測試

@SpringBootTest
@RunWith(SpringRunner.class)
@Component
public class SpringRedisTest {

    @Autowired
    private RedisService<String, Users> redisService;

    @Test
    public void set(){
        Users user = new Users();
        user.setUserId(1L);
        user.setUsername("tom");
        user.setPassword("123");
        redisService.setValue("user_tom", user);
    }

}