application.yml配置文件
spring:
redis:
port: 6379 #端口
host: localhost #ip
database: 0 #库 一共·16个 0-15
config文件 配置了之后不会乱码
@Configuration
public class RedisConfigurtion {
@Autowired
private RedisTemplate redisTemplate;
@Bean
public RedisTemplate<String, Object> stringSerializerRedisTemplate() {
RedisSerializer<String> stringSerializer = new StringRedisSerializer();
redisTemplate.setKeySerializer(stringSerializer);
redisTemplate.setValueSerializer(stringSerializer);
redisTemplate.setHashKeySerializer(stringSerializer);
redisTemplate.setHashValueSerializer(stringSerializer);
return redisTemplate;
}
}
测试
@RunWith(SpringRunner.class)
@SpringBootTest
class RedisCacheTest {
@Autowired
private RedisTemplate redisTemplate;
@Test
void set() {
BoundValueOperations test = redisTemplate.boundValueOps("test");
test.set("测试");
}
}
可以绑定6种类型 与测试例子大同小异 就不一一演示了
pom依赖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<maven.compiler.encoding>UTF-8</maven.compiler.encoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
</dependencies>