Redis detalles de uso

  • Redis es una base de datos de alto rendimiento clave-valor, utilizando el lenguaje C, Redis nombre completo: Diccionario remota del servidor (Remote Data Service), Redis utiliza para almacenar algunos datos requieren la recuperación frecuente, el ahorro de sobrecarga de memoria, sino también en gran medida mejorar la velocidad, almacenada en algunos datos Redis calientes, utilizar el tiempo, tomado de la memoria, que mejora en gran medida la velocidad y el ahorro de los gastos generales del servidor directamente.
  • Uso ReDiS las ideas de caché: En primer lugar, establecer una caché local: ConcurrentHashMap, a continuación, genere datos de objeto RedisTemplate para determinar cuándo tomar la caché local y Redis no hay datos.
  • Entonces alguien preguntó: ¿por qué ReDiS que, con el mapa como una caché local directamente en la línea ah. De hecho, la caché local sólo reduce el número y la hora de los Redis de consulta, pero cuando se produce la situación Tomcat reinicio, se borrará la caché local, pero los datos en caché también es de Redis.
  • base de datos relacional tradicional para cumplir con el ácido, y Redis es un proceso sencillo, la base de datos por defecto 16.
  • La base de datos NoSQL clásica no relacional a conocer a dos de la PAC, no puede cumplir con los tres tipos
  1. C: fuerte consistencia
  2. A: Alta disponibilidad
  3. P: tolerancia a fallos partición
  • Aquí nos fijamos en la configuración de la agrupación de conexiones Redis
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;
    }

}

  • Después de la clase de configuración de escritura le encanta escribir una interfaz

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);
}

  • Entonces escribimos una clase de implementación que implementa la interfaz anterior, la operación de Redis
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;
    }
    
}

  • Después de escribir estos, se puede utilizar directamente
@RestController
@RequestMapping("/consumer/")
public class TestConsumerApi {

    @Autowired
    @Lazy
    RedisHashConsumerManager redisHashConsumerManager;

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

Publicado 51 artículos originales · ganado elogios 11 · vistas 6079

Supongo que te gusta

Origin blog.csdn.net/weixin_42140261/article/details/104860425
Recomendado
Clasificación