spring boot中使用resid-RedisTemplate

1、項目中導入依賴jar包 這裏用的maven

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-redis</artifactId>
   <version>1.4.7.RELEASE</version>
</dependency>
2、項目配置文件設置redis信息 這裏用的 yml配置文件 

redis:
 host: 
 port: 
 password: 
 pool:
  max-active: 8
  min-idle: 0
  max-idle: 8
  max-wait: 10000
 timeout: 0
database: 9
注意 要在spring:節點下

3、在項目中新建類 讓spring boot啓動時加載  RedisTemplate

package com.prairie.manage.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;

import java.lang.reflect.Method;

/**
 * Created by xxx on 2017/6/25.
 * 加載redis配置信息
 */
@Configuration
@EnableCaching
public class RedisConfiguration {
    @Bean
    public KeyGenerator keyGenerator() {
        return new KeyGenerator() {
            @Override
            public Object generate(Object target, Method method, Object... 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();
            }
        };
    }

    @SuppressWarnings("rawtypes")
    @Bean
    public CacheManager cacheManager(RedisTemplate redisTemplate) {
        RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
        //設置緩存過期時間
        //rcm.setDefaultExpiration(60);//秒
        return rcm;
    }

    @Bean
    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
        StringRedisTemplate template = new StringRedisTemplate(factory);
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        template.setValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }
}
4、新建redisService 實現具體操作redis

@Component
public class RedisService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * key value 形式
     * @param key
     * @param value
     */
    @SuppressWarnings({"unchecked", "rawtypes"})
    public void set(final String key, final String value) {
        redisTemplate.execute(new RedisCallback() {
            public Long doInRedis(RedisConnection connection) throws DataAccessException {
                connection.set(key.getBytes(), value.getBytes());
                return 1L;
            }
        });
    }

    /**
     * set 一個有時間的key 到時間後自動過期
     * @param key
     * @param value
     * @param liveTime  存活時間/秒
     */
    @SuppressWarnings({"unchecked", "rawtypes"})
    public void set(final String key, final String value, final long liveTime) {
        redisTemplate.execute(new RedisCallback() {
            public Long doInRedis(RedisConnection connection) throws DataAccessException {
                connection.setEx(key.getBytes(), liveTime, value.getBytes());
                return 1L;
            }
        });
    }

    /**
     * 根據key 獲取value
     * @param key
     * @return
     */
    @SuppressWarnings({"unchecked", "rawtypes"})
    public String get(final String key) {
        return (String) redisTemplate.execute(new RedisCallback() {
            public Object doInRedis(RedisConnection connection) throws DataAccessException {
                try {
                    return new String(connection.get(key.getBytes()));
                } catch (Exception e) {
                }
                return null;
            }
        });
    }

    /**
     * 自增  key不存在則爲1 key存在則自增
     * @param key
     */
    @SuppressWarnings({"unchecked", "rawtypes"})
    public void incrby(final String key) {
        redisTemplate.execute(new RedisCallback() {
            public Long doInRedis(RedisConnection connection) throws DataAccessException {
                Long incr = connection.incr(key.getBytes());
                return incr;
            }
        });
    }


    /**
     *  自增不存在數值會默認初始化0然後加1,傳入時間後自動銷燬
     * @param key
     * @param liveTime
     */
    public void incrby(final String key,final long liveTime) {
        redisTemplate.execute(new RedisCallback<Object>() {
            public Long doInRedis(RedisConnection connection) throws DataAccessException {
                Long incr = connection.incr(key.getBytes());
                connection.expire(key.getBytes(), liveTime);
                return incr;
            }
        });
    }


    /**
     * 自減
     * @param key
     */
    @SuppressWarnings({"unchecked", "rawtypes"})
    public void decrby(final String key) {
        redisTemplate.execute(new RedisCallback() {
            public Long doInRedis(RedisConnection connection) throws DataAccessException {
                Long incr = connection.decr(key.getBytes());
                return incr;
            }
        });
    }

    /**
     * 刪除key的value
     * @param key
     */
    public void del(final String key){
        redisTemplate.execute(new RedisCallback<Object>(){
            public Long doInRedis(RedisConnection connection) throws DataAccessException {
                return connection.del(key.getBytes());
            }
        });
    }

    /**
     * 根據key查看是否存在 刷新
     * @param key
     * @return
     */
    public boolean hasKey(String key){
       return redisTemplate.hasKey(key);
    }

    /**
     * 根據key刷新過期時間
     * @param key
     * @param timeOut
     * @return
     */
    public boolean refreshLiveTime(String key,long timeOut){
        return redisTemplate.expire(key,timeOut, TimeUnit.SECONDS);
    }


}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章