Redis的使用详情

2 篇文章 0 订阅
  • Redis 是一个高性能的key-value数据库,是使用C语言编写的,Redis全称为: Remote Dictionary Server(远程数据服务),Redis常用来存储一些需要频繁调取的数据,节省内存开销,也极大的提升了速度,将一些热点数据存储到Redis中,要用的时候,直接从内存取,极大的提高了速度和节约了服务器的开销。
  • 使用redis缓存思路:首先建立一个本地缓存:concurrentHashmap,然后建立RedisTemplate对象,当拿数据的时候判断本地缓存与redis中有没有数据。
  • 那么有人问了,这样为什么还要redis呢,直接用map作为本地缓存就行了啊。其实本地缓存只是减少了查询redis的次数与时间,但是当tomcat重启等情况出现时,本地缓存就会清零,但是redis中的缓存数据是还有的。
  • 传统的关系型数据库满足ACID,并且Redis是单进程,默认16个数据库。
  • 经典的noSql非关系型数据库满足CAP的其中两种,不能同时满足三种
  1. C:强一致性
  2. A:高可用性
  3. P:分区容错性
  • 下面我们来看一下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;
    }

}

  • 写完配置类之后爱写一个接口

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

  • 接着我们在写一个实现类,用来实现上面的接口,进行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;
    }
    
}

  • 写完这些之后,就可以直接使用了
@RestController
@RequestMapping("/consumer/")
public class TestConsumerApi {

    @Autowired
    @Lazy
    RedisHashConsumerManager redisHashConsumerManager;

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值