我這裏是在windows上練習,因此這裏的安裝是指在windows上的安裝,操做很是簡單,點擊https://github.com/MicrosoftArchive/redis/releases網址,直接點擊下載解壓就安裝成功。開啓也很簡單:html
1.打開cmd,進入安裝目錄,輸入命令:git
redis-server.exe redis.windows.conf
2.接着新打開一個cmd,原先的cmd不要關閉,否則後續步驟會出錯,接着輸入命令:github
redis-cli.exe -h localhost -p 6379
到這裏windows上的redis已經安裝並打開,能夠正常使用了。redis
1. 添加依賴:spring
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
2.配置redisjson
#redis配置 spring: redis: database: 0 host: localhost port: 6379 password:
3.操做redis須要使用RedisTemplate這個對象,可是須要修改RedisTemplate對象的序列化方式。windows
SDR(spring data redis)默認採用的序列化策略有兩種,一種是String的序列化策略,一種是JDK的序列化策略。
StringRedisTemplate默認採用String的序列化策略
RedisTemplate默認採用JDK的序列化策略
import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.ObjectMapper; 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.core.StringRedisTemplate; import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; @Configuration public class RedisConfiguration { @Bean public RedisTemplate redisTemplate(RedisConnectionFactory factory){ StringRedisTemplate stringRedisTemplate = new StringRedisTemplate(factory); Jackson2JsonRedisSerializer<Object> jsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(Object.class); ObjectMapper mapper = new ObjectMapper(); mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jsonRedisSerializer.setObjectMapper(mapper); //值序列化 stringRedisTemplate.setValueSerializer(jsonRedisSerializer); stringRedisTemplate.afterPropertiesSet(); return stringRedisTemplate; } }
3.簡單測試操做redis:
@RunWith(SpringRunner.class) @SpringBootTest public class PsringbootdemoApplicationTests { private static final Logger logger = LoggerFactory.getLogger(PsringbootdemoApplicationTests.class); @Resource RedisTemplate redisTemplate; @Test public void testRedis(){ logger.info("測試redis"); redisTemplate.opsForValue().set("lll","sgf"); String value = (String) redisTemplate.opsForValue().get("lll"); System.out.println(value); } }
結果以下:springboot
RedisTemplate中定義了對5種數據結構操做數據結構
redisTemplate.opsForValue();//操做字符串 redisTemplate.opsForHash();//操做hash redisTemplate.opsForList();//操做list redisTemplate.opsForSet();//操做set redisTemplate.opsForZSet();//操做有序set
具體的操做能夠查看源碼,或者推薦查看這篇博客Spring中使用RedisTemplate操做Redis(spring-data-redis)app