Redis usage details

  • Redis is a high-performance key-value database, using the C language, Redis full name: Remote Dictionary Server (Remote Data Service), Redis used to store some data require frequent retrieval, saving memory overhead, but also greatly enhance the speed, stored in some hot Redis data, use the time, taken from memory, which greatly improves the speed and saving the overhead of the server directly.
  • Use redis cache ideas: First, establish a local cache: concurrentHashmap, then build RedisTemplate object data to determine when to take the local cache and redis there is no data.
  • Then someone asked, so why redis it, with the map as a local cache directly on the line ah. In fact, the local cache only reduces the number and time of the query redis, but when the situation tomcat reboot occurs, the local cache will be cleared, but the cached data is also of redis.
  • Traditional relational database to meet the ACID, and Redis is a single process, the default 16 database.
  • The classic noSql non-relational database to meet two of the CAP, can not meet the three kinds
  1. C: strong consistency
  2. A: High Availability
  3. P: partition fault tolerance
  • Here we look at the configuration of the connection pool 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;
    }

}

  • After writing configuration class loves to write an interface

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

  • Then we write an implementation class that implements the above interface, the operation of 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;
    }
    
}

  • After writing these, you can directly use
@RestController
@RequestMapping("/consumer/")
public class TestConsumerApi {

    @Autowired
    @Lazy
    RedisHashConsumerManager redisHashConsumerManager;

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

Published 51 original articles · won praise 11 · views 6079

Guess you like

Origin blog.csdn.net/weixin_42140261/article/details/104860425