redisConfig和redisUtil


import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
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.context.annotation.Primary;
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 org.springframework.data.redis.serializer.StringRedisSerializer;


@Configuration
@EnableCaching
public class RedisConfig {

	@Autowired
	private StringRedisTemplate stringRedisTemplate;

	/**
	 * generator key generator.
	 *
	 * @return the key generator
	 */
	@Bean
	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();
		};

	}

	/**
	 * Cache manager cache manager.
	 *
	 * @param redisTemplate the redis template
	 *
	 * @return the cache manager
	 */
	@Bean
	public CacheManager cacheManager(RedisTemplate redisTemplate) {
		return new RedisCacheManager(redisTemplate);
	}

	@Bean
	public StringRedisSerializer stringRedisSerializer() {
		return new StringRedisSerializer();
	}

	@Bean("redisTemplate")
	@Primary
	public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
		RedisTemplate<String, Object> template = new RedisTemplate<>();
		template.setConnectionFactory(factory);
		Jackson2JsonRedisSerializer<Object> 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.setKeySerializer(stringRedisSerializer());
		template.setHashKeySerializer(stringRedisSerializer());
		template.setHashValueSerializer(jackson2JsonRedisSerializer);
		template.afterPropertiesSet();
		return template;
	}
}

import com.paascloud.base.constant.CommonConstants;
import com.paascloud.base.exception.ParamException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class RedisUtil {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public RedisUtil() {
    }

    public void set(String key, String value) throws Exception {
        this.stringRedisTemplate.opsForValue().set(key, value);
    }

    public void setObject(String key, Object value) throws Exception {
        this.redisTemplate.opsForValue().set(key, value);
    }

    public void setexObject(String key, Object value, long time) throws Exception {
        this.redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
    }

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

    public String get(String key)  {
        return (String)this.stringRedisTemplate.opsForValue().get(key);
    }

    public void setex(String key, String value, long time) throws Exception {
        this.stringRedisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
    }

    public void hset(String key, String field, String value) throws Exception {
        this.redisTemplate.opsForHash().put(key, field, value);
    }

    public void hset(String key, String field, Object value) throws Exception {
        this.redisTemplate.opsForHash().put(key, field, value);
    }

    public Map<Object, Object> hscan(String key, String hasKey) throws Exception {
        Cursor<Map.Entry<Object, Object>> cursor = this.redisTemplate.opsForHash().scan(key, ScanOptions.scanOptions().match(new StringBuffer("*").append(hasKey).append("*").toString()).count(1).build());
        Map<Object, Object> hashMap = new HashMap<>();
        while(cursor.hasNext()){
            Map.Entry<Object, Object> next = cursor.next();
            hashMap.put(next.getKey(), next.getValue());
        }
        cursor.close();
        return hashMap;
    }

    public void hdelValue(String key, String field) throws Exception {
        this.redisTemplate.opsForHash().delete(key, field);
    }
    public void hdelValue(String key) throws Exception {
        this.redisTemplate.opsForHash().delete(key);
    }


    public String hget(String key, String field) throws Exception {
        return (String)this.redisTemplate.opsForHash().get(key, field);
    }

    public Map<Object,Object> hgetall(String key) throws Exception {
        return this.redisTemplate.opsForHash().entries(key);
    }

    public Object hgetObject(String key, String field) throws Exception {
        return this.redisTemplate.opsForHash().get(key, field);
    }

    public <T> List<T> hgetObjectList(String key, Collection fields) throws Exception {
        return (List<T>)this.redisTemplate.opsForHash().multiGet(key, fields);
    }

    public Long incr(String key) throws Exception {
        return this.redisTemplate.opsForValue().increment(key, 1L);
    }

    public boolean hasKey(String key) throws Exception {
        return this.redisTemplate.hasKey(key);
    }

    public void setex(String key, long value) throws Exception {
        this.redisTemplate.opsForValue().increment(key, value);
    }

    public void expire(String key, Integer seconds) throws Exception {
        this.redisTemplate.expire(key, (long)seconds, TimeUnit.SECONDS);
    }

    public List<String> smembers(String key) throws Exception {
        List<String> list = (List)this.redisTemplate.opsForValue().get(key);
        return list;
    }

    public void setValToList(String key, String val) throws Exception {
        this.redisTemplate.opsForSet().add(key, new Object[]{val});
    }

    public void setValsToList(String key, String[] val) throws Exception {
        this.redisTemplate.opsForSet().add(key, val);
    }

    public Set<Object> getSetmembers(String key) throws Exception {
        return this.redisTemplate.opsForSet().members(key);
    }

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

    public Set<String> keys(String val) throws Exception {
        return this.redisTemplate.keys(val);
    }

    public boolean keyExist(String key) {
        Long size = this.redisTemplate.opsForList().size(key);
        return size >= 1L;
    }

    public void setValToListLeftOne(String key, String value) {
        this.redisTemplate.opsForList().leftPush(key, value);
    }

    public void getValToListLeftOne(String key) {
        this.redisTemplate.opsForList().leftPop(key, 2L, TimeUnit.SECONDS);
    }

    /**
     * 设置List类型对象专用
     * @param key
     * @param value
     * @param <T>
     */
    public <T> Long setValToListLeft(String key, List<T> value) {
        return this.redisTemplate.opsForList().leftPush(key, value);
    }

    /**
     * 获得List类型对象专用
     * @param key
     * @return
     */
    public Object getValToListLeft(String key) {
        return this.redisTemplate.opsForList().leftPop(key);
    }

    /**
     * 设置List类型对象专用
     * @param key
     * @param value
     * @param <T>
     */
    public <T> Long setValToListRight(String key, List<T> value) {
        return this.redisTemplate.opsForList().rightPush(key, value);
    }

    public <T> Long setValToStringRight(String key, String value) {
        return this.stringRedisTemplate.opsForList().rightPush(key, value);
    }

    /**
     * 设置对象专用
     * @param key
     * @param <T>
     */
    public <T> Long setValToObjectRight(String key, Object value) {
        return this.redisTemplate.opsForList().rightPush(key, value);
    }

    /**
     * 获得对象专用
     * @param key
     * @return
     */
    public Object getValToObjectRight(String key) {
        return this.redisTemplate.opsForList().rightPop(key);
    }

    /**
     * 获得List类型对象专用
     * @param key
     * @param l
     * @param l1
     * @return
     */
    public Object getValToListRight(String key, long l, long l1) {
        return this.redisTemplate.opsForList().rightPop(key);
    }

    public Object getValToListRange(String key,long start,long end){
        return this.stringRedisTemplate.opsForList().range(key,start,end );
    }

    /**
     * 获取今日的免鉴权token
     * @return
     */
    public String getTodaySysToken() {
        String token = this.stringRedisTemplate.opsForValue().get(CommonConstants.PASSKEY);
        if(token == null || "".equals(token)){
            throw new ParamException(new Date() + "token为空");
        }
        return token;
    }

    public Object hgetObjectBykey(String key,String field)  {
        try {
            return this.hgetObject(key,field);
        } catch (Exception e) {
            log.error("redisUtils hgetObjectBykey Exception: ", e);
            return null;
        }
    }

    public <T> Map<Object, T> hgetMapByKey(String key,Class<T> clz)  {
        try {
            return (Map<Object, T>)this.hgetall(key);
        } catch (Exception e) {
            log.error("redisUtils setObject Exception: ", e);
            return null;
        }
    }
}

spring:
  redis:
    host: 192.168.0.163
    password: 123456
    port: 6379
    database: 0
    pool:
      max-active: 10

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值