centos7安装Redis
cd /usr/local/src
wget http://download.redis.io/releases/redis-5.0.2.tar.gz
tar xzvf redis-5.0.2.tar.gz
cd redis-5.0.2
make
若遇到如下問題
make[2]: *** [hiredis] Error 2
make[2]: Leaving directory `/usr/software/redis/redis-5.0.2/deps'
make[1]: [persist-settings] Error 2 (ignored)
CC adlist.o
/bin/sh: cc: command not found
make[1]: *** [adlist.o] Error 127
make[1]: Leaving directory `/usr/software/redis/redis-5.0.2/src'
make: *** [all] Error 2
执行
make MALLOC=libc
make install
启动
./src/redis-server
修改配置文件
vi redis.conf
设置开机自启
新建一个系统服务文件
vi /etc/systemd/system/redis.service
[Unit]
Description=redis-server
After=network.target
[Service]
Type=forking
ExecStart=/usr/local/bin/redis-server /usr/software/redis/redis-5.0.2/redis.conf
PrivateTmp=true
[Intall]
WantedBy=muti-user.target
重启系统服务
systemctl daemon-reload
设置开机自启
systemctl enable redis
springboot连接redis
引入依赖:
<!-- spring boot redis缓存引入 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- lecttuce 缓存连接池-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
参数配置:
spring:
redis:
host: 192.168.56.101
port: 6379
password: 123456
lettuce:
pool:
max-active: 8
max-idle: 8
min-idle: 0
max-wait: 100ms
需要关闭linux端的防火墙,否则连接报错
systemctl stop firewalld.service
测试
package com.qq.springsecurity;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
@SpringBootTest
class SpringSecurityApplicationTests {
@Autowired
private RedisTemplate redisTemplate;
@Autowired
private StringRedisTemplate stringRedisTemplate;
private static final ObjectMapper mapper = new ObjectMapper();
@Test
void testString(){
redisTemplate.opsForValue().set("name","tom");
Object name =redisTemplate.opsForValue().get("name");
System.out.println("name="+name);
}
@Test
void testStringRedis() throws JsonProcessingException {
//准备对象
User user =new User("tom",18);
// System.out.println(user);
//手动序列化
String json =mapper.writeValueAsString(user);
//写入一条数据到redis
stringRedisTemplate.opsForValue().set("user:200",json);
//读取数据
String val =stringRedisTemplate.opsForValue().get("user:200");
//反序列化
User user1 = mapper.readValue(val,User.class);
System.out.println(user1);
}
}