本文共 2914 字,大约阅读时间需要 9 分钟。
4.0.0 com.learn springboot2.0-redis 0.0.1-SNAPSHOT org.springframework.boot spring-boot-starter-parent 1.5.12.RELEASE org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-data-redis
###########################################################Redis (RedisConfiguration)########################################################spring.redis.database=0spring.redis.host=localhostspring.redis.port=6379spring.redis.password=123456spring.redis.pool.max-idle=8spring.redis.pool.min-idle=0spring.redis.pool.max-active=8spring.redis.pool.max-wait=-1spring.redis.timeout=5000
package com.learn.service;import java.util.Set;import java.util.concurrent.TimeUnit;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.data.redis.core.StringRedisTemplate;import org.springframework.stereotype.Component;// springboot 2.0 整合redis@Componentpublic class RedisService { @Autowired private StringRedisTemplate stringRedisTemplate; public void set(String key, Object object, Long time) { // 让该方法能够支持多种数据类型存放 if (object instanceof String) { setString(key, object); } // 如果存放时Set类型 if (object instanceof Set) { setSet(key, object); } // 设置有效期 if (time != null) { stringRedisTemplate.expire(key, time, TimeUnit.SECONDS); } } public void setString(String key, Object object) { String value = (String) object; // 存放string类型 stringRedisTemplate.opsForValue().set(key, value); } public void setSet(String key, Object object) { SetvalueSet = (Set ) object; for (String string : valueSet) { stringRedisTemplate.opsForSet().add(key, string); } } public String getString(String key) { return stringRedisTemplate.opsForValue().get(key); }}
package com.api.controller;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import com.learn.service.RedisService;@RestControllerpublic class IndexController { @Autowired private RedisService redisService; @RequestMapping("/setString") public String setString(String key, String object) { redisService.set(key, object, 60l); return "success"; } @RequestMapping("/get") public String get(String key) { return redisService.getString(key); }}
package com;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplicationpublic class App { public static void main(String[] args) { SpringApplication.run(App.class, args); }}
localhost:8080/setString?key=leon&object=123456localhost:8080/get?key=leon
转载地址:http://mfkzb.baihongyu.com/