一、配置服务机环境
1、centos安装redis
进入centos终端:
(1)下载redis的压缩文件到指定的目录:wget http://download.redis.io/releases/redis-4.0.2.tar.gz
(2)加压压缩文件:tar xzf redis-4.0.2.tar.gz
(3) 进入压缩后的文件 cd redis-4.0.2
(4)执行安装命令 make make install
(5)启动redis,检测是否安装成功:redis-server
调用redis客户端测试redis存取键值对
进入redis客户端可以看到redis的host和port
(6)设置redis密码
进入root的redis目录: cd redis-4.0.2
vi命令打开redis.conf,找到下图的#requirepass foobared去掉#,改为requirepass 123456
修改redis的host(注释掉本机host:127.0.0.1,修改为虚拟机的ip), 关闭掉redis的保护模式,不然远程连接会失败
二、后台代码配置redis
1、pom.xml文件加入reids依赖
org.springframework.boot
spring-boot-starter-redis
application配置redis参数
spring.redis.database=0
spring.redis.host=192.168.137.133
spring.redis.port=6379
spring.redis.password=123456
spring.redis.jedis.pool.max-idle=8
spring.redis.jedis.pool.min-idle=0
2、创建redis的工具
package cn.fcw.bb.webapply.redis;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
@Configuration
@EnableCaching
public class RedisConfigurer extends CachingConfigurerSupport {
@Bean
public RedisTemplate redisTemplate(RedisConnectionFactory factory) {
StringRedisTemplate template = new StringRedisTemplate(factory);
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
template.setValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
@Bean
public KeyGenerator keyGenerator() {
return (target, method, params) -> {
StringBuilder sb = new StringBuilder();
sb.append(target.getClass().getName());
sb.append(method.getName());
for (Object obj : params) {
sb.append(obj.toString());
}
return sb.toString();
};
}
@SuppressWarnings("rawtypes")
@Bean
public CacheManager cacheManager(RedisConnectionFactory factory) {
// RedisCacheConfiguration redisCacheConfiguration=RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofHours(1));
// return RedisCacheManager.builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory))
// .cacheDefaults(redisCacheConfiguration).build();
return RedisCacheManager.create(factory);
}
}
package cn.fcw.bb.webapply.redis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.*;
import org.springframework.stereotype.Component;
import java.io.Serializable;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
@Component
public class RedisUtils {
@Autowired
private RedisTemplate redisTemplate;
/**
* 写入缓存
* @param key
* @param value
* @return
*/
public boolean set(final String key, Object value) {
boolean result = false;
try {
ValueOperations operations = redisTemplate.opsForValue();
operations.set(key, value);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 写入缓存设置时效时间
* @param key
* @param value
* @return
*/
public boolean set(final String key, Object value, Long expireTime , TimeUnit timeUnit) {
boolean result = false;
try {
ValueOperations operations = redisTemplate.opsForValue();
operations.set(key, value);
redisTemplate.expire(key, expireTime, timeUnit);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 批量删除对应的value
* @param keys
*/
public void remove(final String... keys) {
for (String key : keys) {
remove(key);
}
}
/**
* 批量删除key
* @param pattern
*/
public void removePattern(final String pattern) {
Set keys = redisTemplate.keys(pattern);
if (keys.size() > 0){
redisTemplate.delete(keys);
}
}
/**
* 删除对应的value
* @param key
*/
public void remove(final String key) {
if (exists(key)) {
redisTemplate.delete(key);
}
}
/**
* 判断缓存中是否有对应的value
* @param key
* @return
*/
public boolean exists(final String key) {
return redisTemplate.hasKey(key);
}
/**
* 读取缓存
* @param key
* @return
*/
public Object get(final String key) {
Object result = null;
ValueOperations operations = redisTemplate.opsForValue();
result = operations.get(key);
return result;
}
/**
* 哈希 添加
* @param key
* @param hashKey
* @param value
*/
public void hmSet(String key, Object hashKey, Object value){
HashOperations hash = redisTemplate.opsForHash();
hash.put(key,hashKey,value);
}
/**
* 哈希获取数据
* @param key
* @param hashKey
* @return
*/
public Object hmGet(String key, Object hashKey){
HashOperations hash = redisTemplate.opsForHash();
return hash.get(key,hashKey);
}
/**
* 列表添加
* @param k
* @param v
*/
public void lPush(String k,Object v){
ListOperations list = redisTemplate.opsForList();
list.rightPush(k,v);
}
/**
* 列表获取
* @param k
* @param l
* @param l1
* @return
*/
public List
3、redis业务应用 将用户信息存储到redis的数据库
@RunWith(SpringRunner.class)
@SpringBootTest
public class RedisTest {
@Autowired
private IUserMapper userMapper;
@Autowired
private RedisUtils redisUtils;
@Test
public void addObject(){ //把userBean对象存入redis
UserBean userBean= userMapper.findUserById(2);
System.out.println("user="+userBean.toString());
redisUtils.set("user",userBean);
}
@Test
public void redisListTest(){ //向redis中存入一个key为list的集合
redisUtils.add("list","Spring");
redisUtils.add("list","EBJ");
redisUtils.add("list","Hibernate");
redisUtils.add("list","Struts2");
}
}
三、使用Redis Desktop Manager可视化工具查看redis数据库