第一步:在pom.xml中加入redis依赖包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
第二步:创建config配置类RedisConfig
package com.tedu.redisdemo.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
/**
* Spring的配置类,用于配置Redis
* 在里面维护一个RedisTemple,用于让Spring IOC容器帮我们在需要的地方自动注入该类
*/
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Serializable> initRedisTemplate(
RedisConnectionFactory redisConnectionFactory){
//初始化Redis的模板类
RedisTemplate<String, Serializable> redisTemplate = new RedisTemplate<>();
//为模板类设置链接工厂
redisTemplate.setConnectionFactory(redisConnectionFactory);
//key序列化为字符串形式
redisTemplate.setKeySerializer(RedisSerializer.string());
/**
* set("张三",person)
* class Person{
* private String name;
* private int age;
* }
* set 张三 {"name": "张三","age": "22"}
*
*/
redisTemplate.setValueSerializer(RedisSerializer.json());
//设置hash的序列化器
redisTemplate.setHashKeySerializer(RedisSerializer.json());
redisTemplate.setHashValueSerializer(RedisSerializer.json());
return redisTemplate;
}
}
第三步:在application.properties中加入连接
server.port=8080
//连接liux远程redis服务
spring.redis.host=192.168.175.128
spring.redis.port=6379
spring.redis.password=123456
spring.redis.database=0
//连接本地redis服务
spring.redis.host=localhost
spring.redis.port=6379
第四步:写测试类
//首先先注入
@Autowired
private RedisTemplate<String, Serializable> redisTemplate;
//实现
@Test
void contextLoads() {
//创建一个用于操作SET GET命令的操作对象,进行普通的SET key value 和 GET key操作
ValueOperations<String,Serializable> ops = redisTemplate.opsForValue();
//SET hello world
ops.set("hello","world");
//GET hello
System.out.println(ops.get("hello"));
User user = new User(1,"张三","123456");
ops.set("张三",user);
User u = (User)ops.get("张三");
System.out.println(u);
}