- Redis 是一个高性能的key-value数据库,是使用C语言编写的,Redis全称为: Remote Dictionary Server(远程数据服务),Redis常用来存储一些需要频繁调取的数据,节省内存开销,也极大的提升了速度,将一些热点数据存储到Redis中,要用的时候,直接从内存取,极大的提高了速度和节约了服务器的开销。
- 使用redis缓存思路:首先建立一个本地缓存:concurrentHashmap,然后建立RedisTemplate对象,当拿数据的时候判断本地缓存与redis中有没有数据。
- 那么有人问了,这样为什么还要redis呢,直接用map作为本地缓存就行了啊。其实本地缓存只是减少了查询redis的次数与时间,但是当tomcat重启等情况出现时,本地缓存就会清零,但是redis中的缓存数据是还有的。
- 传统的关系型数据库满足ACID,并且Redis是单进程,默认16个数据库。
- 经典的noSql非关系型数据库满足CAP的其中两种,不能同时满足三种
- C:强一致性
- A:高可用性
- 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;
@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 jacksonSeial = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jacksonSeial.setObjectMapper(om);
template.setValueSerializer(jacksonSeial);
template.setKeySerializer(new StringRedisSerializer());
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);
}
@Override
public String addConsumer(Map<String, Object> consumer) {
String consumerToken = (String) consumer.get("token");
redisHas.putAll(consumerToken, consumer);
redisTemplate.expire(consumerToken, getActivityTime(), getActivityTimeUnit());
return consumerToken;
}
@Override
public void deleteConsumer(String token) {
redisTemplate.delete(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);
}
@Override
public void delParameter(String token, String key) {
if (hasConsumer(token))
redisHas.delete(token, key);
}
@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);
}
}