使用Spring Boot整合Redis操作快取
阿新 • • 發佈:2018-12-19
下來操作SpringBoot整合Redis 首先Redis是一個開源(BSD許可)的,記憶體中的資料結構儲存系統,它可以用作資料庫,快取和訊息中介軟體
1)使用docker安裝redis 如果沒有安裝Redis, 請使用以下命令安裝:
[[email protected] ~]# docker pull registry.docker-cn.com/library/redis
2)引入redis的starter 匯入redis驅動包spring-boot-starter-data-redis 在pom.xml配置檔案中配置如下引數:
<!--匯入redis驅動包--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
3)配置redis,在application.properties配置檔案中配置Redis的地址, 使用如下命令: 值為虛擬機器的ip
4.配置自定義的RedisTemplate序列化規則
@Configuration public class MyRedisConfig { /** * 自定義轉換序列化,如果使用預設儲存物件序列化,則在redis中儲存的資料顯示的是機器碼 * @param redisConnectionFactory * @return * @throws UnknownHostException */ @Bean public RedisTemplate<Object, Employee> empredisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException { RedisTemplate<Object, Employee> template = new RedisTemplate(); template.setConnectionFactory(redisConnectionFactory); Jackson2JsonRedisSerializer<Employee> ser = new Jackson2JsonRedisSerializer<Employee>(Employee.class); template.setDefaultSerializer(ser); return template; } }
5.配置測試類
@RunWith(SpringRunner.class) @SpringBootTest public class Springboot01CacheApplicationTests { @Autowired EmployeeMapper employeeMapper; //引入redis驅動包後,就有了RedisConfiguration類以下兩個類是這個類中的 //StringRedisTemplate類是操作k-v都是字串的 @Autowired StringRedisTemplate stringRedisTemplate; //RedisTemplate類是操作k-v都是物件的 @Autowired RedisTemplate redisTemplate; //使用配置的自定義方法轉換序列化,如果使用預設儲存物件序列化,則在redis中儲存的資料顯示的是機器碼 @Autowired RedisTemplate<Object, Employee> empredisTemplate; /** * Redis常見的五大資料型別 * String(字串),List(列表),Set(集合),Hash(雜湊),Zset(有序集合) * stringRedisTemplate.opsForValue() 是來操作String(字串的)的 * stringRedisTemplate.opsForList() 是來操作List(列表)的 * stringRedisTemplate.opsForSet() 是來操作Set(集合)的 * stringRedisTemplate.opsForHash() 是來操作Hash(雜湊)的 * stringRedisTemplate.opsForZSet() 是來操作Zset(有序集合)的 * StringRedisTemplate和RedisTemplate操作的方法是一模一樣的, 只是一個操作字串的一個操作物件的 */ @Test public void test01() { //給redis添加了一個key鍵msg值為hello //stringRedisTemplate.opsForValue().append("msg","hello"); //讀取redis中的資料 /*String msg = stringRedisTemplate.opsForValue().get("msg"); System.out.println(msg);*/ //操作List stringRedisTemplate.opsForList().leftPush("mylist", "1"); stringRedisTemplate.opsForList().leftPush("mylist", "2"); } /** * 操作物件 * 在操作物件之前,實體類必須實現序列化 */ @Test public void test02() { Employee employee = employeeMapper.getEmpById(1); //預設如果儲存物件,使用jdk序列化機制,序列化後的資料儲存到redis中 /* redisTemplate.opsForValue().set("emp-01",employee);*/ //1.將資料以json方式儲存 // 1)自己將物件轉為json // 2)redisTemplate預設的序列化規則,改變預設的序列化規則 //使用配置的自定義方法轉換序列化,如果使用預設儲存物件序列化,則在redis中儲存的資料顯示的是機器碼 empredisTemplate.opsForValue().set("emp-01", employee); }