1.导入Spring Data Redis的maven坐标
pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2. 配置Redis数据源
2.1application.yml文件
datasource:druid:driver-class-name: ${sky.datasource.driver-class-name}url: jdbc:mysql://${sky.datasource.host}:${sky.datasource.port}/${sky.datasource.database}?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=trueusername: ${sky.datasource.username}password: ${sky.datasource.password} # redis数据连接redis:host: ${sky.redis.host}port: ${sky.redis.port}password: ${sky.redis.password}database: ${sky.redis.database}
2.2application-dev.yml文件
sky:datasource:driver-class-name: com.mysql.cj.jdbc.Driverhost: localhostport: 3306database: sky_take_outusername: rootpassword: 123456redis:host: localhostport: 6379password: 123456database: 10
3. 编写配置类,创建RedisTemplate对象
package com.sky.config;import lombok.extern.slf4j.Slf4j;
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.StringRedisSerializer;@Configuration
@Slf4jpublic class RedisConfiguration {@Beanpublic RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) {log.info("开始创建redis");RedisTemplate redisTemplate = new RedisTemplate();
// 设置redis的连接工厂对象redisTemplate.setConnectionFactory(redisConnectionFactory);
// 设置redis key的序列化器redisTemplate.setKeySerializer(new StringRedisSerializer());return redisTemplate;}
}
4.通过RedisTemplate对象操作Redis
说明:编写测试类
package com.sky.test;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.*;import java.sql.Time;
import java.util.concurrent.TimeUnit;@SpringBootTest
public class SpringDataRedisTest {@Autowiredprivate RedisTemplate redisTemplate;@Testpublic void testRedisTemplate() {System.out.println(redisTemplate);ValueOperations valueOperations = redisTemplate.opsForValue();HashOperations hashOperations = redisTemplate.opsForHash();ListOperations listOperations = redisTemplate.opsForList();SetOperations setOperations = redisTemplate.opsForSet();}/*操作字符串类型的数据** */@Testpublic void testString() {//set get setex setnxredisTemplate.opsForValue().set("city", "北京");String city = (String) redisTemplate.opsForValue().get("city");System.out.println(city);redisTemplate.opsForValue().set("code","1234",3, TimeUnit.MINUTES);
// setnxredisTemplate.opsForValue().setIfAbsent("lock","1");redisTemplate.opsForValue().setIfAbsent("lock","2");}
}
5.结果