1. 引入jar文件。java
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <!-- https://mvnrepository.com/artifact/redis.clients/jedis --> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> </dependency>
jedis是必需要的驅動文件,不然運行程序時會出現錯誤:web
org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.data.redis.connection.RedisConnectionFactory' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
2. 配置文件redis
# application.properties spring.redis.database=0 spring.redis.host=127.0.0.1 spring.redis.port=6379 spring.redis.password= spring.redis.jedis.pool.max-active=8 spring.redis.jedis.pool.max-wait=-1 spring.redis.jedis.pool.max-idle=8 spring.redis.jedis.pool.min-idle=0 spring.redis.timeout=5000
3. 還須要本身寫相關的配置spring
@Configuration public class RedisConfig { /** * 注入 RedisConnectionFactory */ @Autowired RedisConnectionFactory redisConnectionFactory; /** * 實例化 RedisTemplate 對象 * * @return */ @Bean public RedisTemplate<String, Object> functionDomainRedisTemplate() { RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>(); initDomainRedisTemplate(redisTemplate, redisConnectionFactory); return redisTemplate; } /** * 設置數據存入 redis 的序列化方式 * * @param redisTemplate * @param factory */ private void initDomainRedisTemplate(RedisTemplate<String, Object> redisTemplate, RedisConnectionFactory factory) { redisTemplate.setKeySerializer(new StringRedisSerializer()); redisTemplate.setHashKeySerializer(new StringRedisSerializer()); redisTemplate.setHashValueSerializer(new JdkSerializationRedisSerializer()); redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer()); redisTemplate.setConnectionFactory(factory); } /** * 實例化 HashOperations 對象,能夠使用 Hash 類型操做 * * @param redisTemplate * @return */ @Bean public HashOperations<String, String, Object> hashOperations(RedisTemplate<String, Object> redisTemplate) { return redisTemplate.opsForHash(); } /** * 實例化 ValueOperations 對象,能夠使用 String 操做 * * @param redisTemplate * @return */ @Bean public ValueOperations<String, Object> valueOperations(RedisTemplate<String, Object> redisTemplate) { return redisTemplate.opsForValue(); } /** * 實例化 ListOperations 對象,能夠使用 List 操做 * * @param redisTemplate * @return */ @Bean public ListOperations<String, Object> listOperations(RedisTemplate<String, Object> redisTemplate) { return redisTemplate.opsForList(); } /** * 實例化 SetOperations 對象,能夠使用 Set 操做 * * @param redisTemplate * @return */ @Bean public SetOperations<String, Object> setOperations(RedisTemplate<String, Object> redisTemplate) { return redisTemplate.opsForSet(); } /** * 實例化 ZSetOperations 對象,能夠使用 ZSet 操做 * * @param redisTemplate * @return */ @Bean public ZSetOperations<String, Object> zSetOperations(RedisTemplate<String, Object> redisTemplate) { return redisTemplate.opsForZSet(); } }
4. 使用:緩存
// hash的使用: @Resource private RedisTemplate<String, Object> objRedisTemplate; void test() { // ...... // 這裏的PublicUser 爲本身定義的一個實體類文件,也就是咱們要存儲的user信息 HashOperations<String, String, PublicUser> hashOperations = objRedisTemplate.opsForHash(); // user就是上面所寫的PublicUser hashOperations.put("public_user", "user1", user); // 這裏是從redis取數據。 PublicUser user2 = hashOperations.get("public_user", "user1"); // ...... }
// StringRedisTemplate @Autowired private StringRedisTemplate stringRedisTemplate; /** * 操做字符串 */ private void operateString() { stringRedisTemplate.opsForValue().set("author", "luoliang"); String value = stringRedisTemplate.opsForValue().get("author"); log.info("stringRedisTemplate輸出值:{}", value); } /** * Redis List操做,Redis列表是簡單的字符串列表,按照插入順序排序。能夠添加一個元素到列表的頭部(左邊)或者尾部(右邊) */ private void operateList() { String key = "website"; ListOperations<String, String> listOperations = stringRedisTemplate.opsForList(); //從左壓入棧 listOperations.leftPush(key, "Github"); listOperations.leftPush(key, "CSDN"); //從右壓入棧 listOperations.rightPush(key, "SegmentFault"); log.info("list size:{}", listOperations.size(key)); List<String> list = listOperations.range(key, 0, 2); list.forEach(log::info); }
若是你只須要簡單的存儲的化,只須要一、2的操做,3的配置文件不須要寫。在使用時以下便可:app
//注入redisTemplate @Autowired private StringRedisTemplate redisTemplate; @Test public void setRedis() { //緩存中最經常使用的方法 redisTemplate.opsForValue().set("first","siwei"); //設置緩存過時時間爲30 單位:秒 //關於TimeUnit下面有部分源碼截圖 redisTemplate.opsForValue().set("second","siweiWu",30, TimeUnit.SECONDS); System.out.println("存入緩存成功"); } @Test public void getRedis(){ String first = redisTemplate.opsForValue().get("first"); String second = redisTemplate.opsForValue().get("second"); System.out.println("取出緩存中first的數據是:"+first); System.out.println("取出緩存中second的數據是:"+second); } @Test public void delRedis() { //根據key刪除緩存 Boolean first1 = redisTemplate.delete("first"); System.out.println("是否刪除成功:"+first1); }
==================================================================================spring-boot
下面時有關redis的擴展用法:ui
stringRedisTemplate.opsForValue().set("test", "100",60*10,TimeUnit.SECONDS);//向redis裏存入數據和設置緩存時間 stringRedisTemplate.boundValueOps("test").increment(-1);//val作-1操做 stringRedisTemplate.opsForValue().get("test")//根據key獲取緩存中的val stringRedisTemplate.boundValueOps("test").increment(1);//val +1 stringRedisTemplate.getExpire("test")//根據key獲取過時時間 stringRedisTemplate.getExpire("test",TimeUnit.SECONDS)//根據key獲取過時時間並換算成指定單位 stringRedisTemplate.delete("test");//根據key刪除緩存 stringRedisTemplate.hasKey("546545");//檢查key是否存在,返回boolean值 stringRedisTemplate.opsForSet().add("123", "1","2","3");//向指定key中存放set集合 stringRedisTemplate.expire("123",1000 , TimeUnit.MILLISECONDS);//設置過時時間 stringRedisTemplate.opsForSet().isMember("123", "1")//根據key查看集合中是否存在指定數據 stringRedisTemplate.opsForSet().members("123");//根據key獲取set集合 // 驗證有效時間 Long expire = redisTemplate.boundHashOps("123").getExpire(); System.out.println("redis有效時間:"+expire+"S");