准备:docker镜像,redis镜像;redis桌面管理工具;redis desktop manager之后所有的代码都在github上:https://github.com/pshdhx/springboot-redis-cache-mysql
1、下载docker中的redis镜像 docker pull redis
2、生成redis容器; docker run -d --name redis1 -p 6379:6379 redis --requirepass "pshdhx"
3、配置dom文件
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
4、application.properities配置redis
spring.redis.host=192.168.55.128
spring.redis.port=6379
spring.redis.password=pshdhx
5、客户端桌面工具连接redis
6、springboot的redis使用
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(RedisOperations.class)
@EnableConfigurationProperties(RedisProperties.class)
@Import({ LettuceConnectionConfiguration.class, JedisConnectionConfiguration.class })
public class RedisAutoConfiguration {
@Bean
@ConditionalOnMissingBean(name = "redisTemplate")
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory)
throws UnknownHostException {
RedisTemplate<Object, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
return template;
}
@Bean
@ConditionalOnMissingBean
public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory)
throws UnknownHostException {
StringRedisTemplate template = new StringRedisTemplate();
template.setConnectionFactory(redisConnectionFactory);
return template;
}
}
/**
* redis常见的五大数据类型
* String(字符串)、list列表、set集合、hash散列、ZSet有序集合
*/
@Autowired
RedisTemplate redisTemplate; //key value 都是对象
@Autowired
StringRedisTemplate stringRedisTemplate; //key和value都是字符串
@Test
public void test1(){
//往redis中保存数据
stringRedisTemplate.opsForValue().append("msg","hello");
}
存储对象时要给实体类实现序列化的接口;
当然也可以使用json方式来缓存对象;
package com.pshdhx.cache.config;
import com.pshdhx.cache.domain.Employee;
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.Jackson2JsonRedisSerializer;
/**
* @Authtor pshdhx
* @Date 2020/12/1420:24
* @Version 1.0
*/
@Configuration
public class MyRedisConfig {
@Bean
public RedisTemplate <Object, Employee> empRedisTemplate(RedisConnectionFactory redisConnectionFactory) throws Exception{
RedisTemplate<Object,Employee> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
Jackson2JsonRedisSerializer<Employee> ser = new Jackson2JsonRedisSerializer<Employee>(Employee.class);
template.setDefaultSerializer(ser);
return template;
}
}
@Autowired
RedisTemplate<Object,Employee> empRedisTemplate;
@Test
public void test2(){
Employee employee = employeemapper.getEmployee(1);
empRedisTemplate.opsForValue().set("emp-01",employee);
}