spring boot配置连接redis样例
一、安装redis
redis使用分为redis单机版、redis主从模式、redis哨兵模式和redis集群模式,本样例为redis单机版
redis下载地址为
https://github.com/microsoftarchive/redis/releases
放入redis文件夹中,解压到redis7000文件夹下
二、配置与启动
修改redis.windows.conf文件
port 7000
其他配置可以不用考虑
新建文本文档start.txt,其中添加以下语句
redis-server.exe redis.windows.conf
将start.txt改为start.bat作为启动文件
三、spring boot程序代码
1.通过maven引入jar包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2.配置application.properties参数
#reids
spring.redis.database= 0
spring.redis.host= 127.0.0.1
spring.redis.port= 7029
spring.redis.password=
spring.redis.jedis.pool.max-active= 2000
spring.redis.jedis.pool.max-idle= 100
spring.redis.jedis.pool.min-idle= 50
3.添加RedisTemplate配置类
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.io.Serializable;
@Configuration
@AutoConfigureAfter(RedisAutoConfiguration.class)
public class RedisConfig {
@Bean
public RedisTemplate<String, Serializable> redisCacheTemplate(LettuceConnectionFactory redisConnectionFactory){
RedisTemplate<String, Serializable> template = new RedisTemplate<>();
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
template.setConnectionFactory(redisConnectionFactory);
return template;
}
}
4.新建测试类
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;
@SpringBootTest
public class myredistest {
@Autowired
private RedisTemplate redisTemplate;
@Test
public void mytest(){
redisTemplate.opsForValue().set("happy","开心");
Object result = redisTemplate.opsForValue().get("happy");
System.out.println(result);
}
}
运行结果