레디 스 사용 정보

  • 뿐만 아니라 크게, 레디 스 일부 데이터는 자주 검색을 필요로 저장하는 데 사용되는 원격 사전 서버 (원격 데이터 서비스) 오버 헤드 메모리 저장 : 레디 스는 C 언어, 레디 스 전체 이름을 사용하여 고성능의 키 - 값 데이터베이스입니다 어떤 뜨거운 레디 스 데이터 저장 속도를 크게 향상 속도와 직접 서버의 오버 헤드 절약을 향상 메모리에서 소요되는 시간을 사용한다.
  • 먼저, 로컬 캐시를 설정 : 사용은 캐시 아이디어를 레디 스 로컬 캐시를 가지고 데이터가없는 레디 스 때 ConcurrentHashMap의 후 결정 RedisTemplate 객체 데이터를 구축 할 수 있습니다.
  • 그런 사람은 왜 선 아에 직접 로컬 캐시로지도, 그것을 레디 스 물었다. 사실, 로컬 캐시는 쿼리 레디 스의 수와 시간을 줄일 수 있지만, 재부팅 바람둥이 상황이 발생했을 때, 로컬 캐시가 삭제됩니다,하지만 캐시 된 데이터는 레디 스의도이다.
  • 전통적인 관계형 데이터베이스는 ACID를 충족하고, 레디 스는 단일 프로세스, 기본 (16) 데이터베이스입니다.
  • 캡의 두 가지를 충족 고전되는 NoSQL 비 관계형 데이터베이스는 3 종류 충족시킬 수 없다
  1. C : 강력한 일관성
  2. A : 고 가용성
  3. P : 파티션 내결함성
  • 여기에서 우리는 연결 풀 레디 스의 구성을 보면
package com.terse.develop.loginmanage.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import redis.clients.jedis.JedisPoolConfig;

/**
 * redis 配置
 */
@Configuration
@EnableAutoConfiguration
public class RedisConfig {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("${spring.redis.hostName}")
    private String host;

    @Value("${spring.redis.port}")
    private int port;

    @Value("${spring.redis.password}")
    private String password;

    @Value("${spring.redis.timeout}")
    private int timeout;

    @Value("${redis.pool.maxWaitMillis}")
    private long maxWaitMillis;

    @Value("${redis.pool.maxIdle}")
    private int maxIdle;

    //连接池
    @Bean("JPC")
    @ConfigurationProperties(prefix = "redis.pool")
    public JedisPoolConfig getRedisConfig() {
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxIdle(maxIdle);
        config.setMaxWaitMillis(maxWaitMillis);
        return config;
    }




    //数据源 --- 工厂
    @Bean("JCF")
    @ConfigurationProperties(prefix = "spring.redis")
    public JedisConnectionFactory getConnectionFactory() {
        JedisConnectionFactory factory = new JedisConnectionFactory();
        JedisPoolConfig config = getRedisConfig();
        factory.setPoolConfig(config);
        factory.setHostName(host);
        factory.setPassword(password);
        factory.setTimeout(timeout);
        logger.info("JedisConnectionFactory bean init success.");
        return factory;
    }

    //操作工具
    @Bean("RT")
    public RedisTemplate<String, Object> redisTemplate(@Qualifier("JCF") RedisConnectionFactory factory) {

        RedisTemplate<String, Object> template = new RedisTemplate<>();
        // 配置连接工厂
        template.setConnectionFactory(factory);

        //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
        Jackson2JsonRedisSerializer jacksonSeial = new Jackson2JsonRedisSerializer(Object.class);

        ObjectMapper om = new ObjectMapper();
        // 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        // 指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会跑出异常
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jacksonSeial.setObjectMapper(om);

        // 值采用json序列化
        template.setValueSerializer(jacksonSeial);
        //使用StringRedisSerializer来序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());

        // 设置hash key 和value序列化模式
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(jacksonSeial);
        template.afterPropertiesSet();

        return template;
    }

}

  • 쓰기 구성 클래스는 인터페이스를 작성하는 사랑 후에

import java.util.Map;

public interface RedisHashConsumerManager<T> {

    //是否存在消费者
    boolean hasConsumer(String token);
    
    //添加消费者
	String addConsumer(Map<String, Object> consumer)

	//删除消费者
    void deleteConsumer(String token);
    
    //获取消费者
    T getConsumer(String token);

    //为某个消费者添加参数和值
    void addParameter(String token, String key, String value);

    //删除某个参数
    void delParameter(String token, String key);

    //获取某个参数
    String getParameter(String token, String key);
}

  • 그럼 우리가 구현 클래스를 작성하는 구현 위의 인터페이스, 레디 스의 작동
import org.springframework.data.redis.core.*;

import javax.annotation.Resource;
import java.util.Map;


public class HashConsumerManageImpl<P, PS> implements RedisHashConsumerManager<Map<String, Object>> {

    protected final HashOperations<String, String, Object> redisHas;
    protected final RedisTemplate<String, Object> redisTemplate;
    protected long activityTime = 7; //多久过期
    protected TimeUnit activityTimeUnit = TimeUnit.DAYS; //时间单位:天

    public HashConsumerManageImpl(RedisTemplate<String, Object> redisTemplate) {
    	this.redisHas = redisTemplate.opsForHash();
        this.redisTemplate = redisTemplate;
    }

	public long getActivityTime() {
        return activityTime;
    }

    public TimeUnit getActivityTimeUnit() {
        return activityTimeUnit;
    }
    
	@Override
    public boolean hasConsumer(String token) {
        return redisTemplate.hasKey(token);//判断当前集合中是否已经存在token
    }
    
    @Override
    public String addConsumer(Map<String, Object> consumer) {
        String consumerToken = (String) consumer.get("token");//获取登陆者信息中的token值
        redisHas.putAll(consumerToken, consumer);//批量向redis hash集合中存放元素
        redisTemplate.expire(consumerToken, getActivityTime(), getActivityTimeUnit());//指定缓存失效时间
        return consumerToken;
    }
    
    @Override
    public void deleteConsumer(String token) {
        redisTemplate.delete(token);// 删除token元素
    }
    
    @Override
    public Map<String, Object> getConsumer(String token) {
        return redisHas.entries(token);//获取集合中的所有元素
    }

    @Override
    public void addParameter(String token, String key, String value) {
        if (hasConsumer(token))
            redisHas.put(token, key, value);//向redis hash几何中存放一个元素
    }

    @Override
    public void delParameter(String token, String key) {
        if (hasConsumer(token))
            redisHas.delete(token, key);//删除map集合中一个或多个token
    }

    @Override
    public String getParameter(String token, String key) {
        if (hasConsumer(token))
            return (String) redisHas.get(token, key);//获取集合中的某个值
        return null;
    }
    
}

  • 이러한를 작성 후, 직접 사용할 수 있습니다
@RestController
@RequestMapping("/consumer/")
public class TestConsumerApi {

    @Autowired
    @Lazy
    RedisHashConsumerManager redisHashConsumerManager;

    @RequestMapping("login")
    public void login(Map<String, Object> consumer) {
        redisHashConsumerManager.addConsumer(consumer);
    }
}

게시 51 개 원래 기사 · 원의 찬양 (11) · 전망 6079

추천

출처blog.csdn.net/weixin_42140261/article/details/104860425