首先引入依赖pom
org.springframework.boot spring-boot-starter-data-redis 2.0.0.RELEASE
编写redis工具类
package cn.itchao.base;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.data.redis.core.StringRedisTemplate;import org.springframework.stereotype.Component;import java.util.Set;import java.util.concurrent.TimeUnit;/** * @author: jinchao * @date: 18/8/9 23:32 * @description: redis操作工具类 */@Componentpublic class BaseRedisService { @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) { if(object instanceof String){ 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); } public void deleteKey(String key){ stringRedisTemplate.delete(key); }}
配置集群链接信息,在application.yml文件中配置
spring: application: name: member-server redis: database: 0#单机版# host: 127.0.0.1# port: 6379# password: 123456# pool:# max-idle: 100# min-idle: 1# max-active: 1000# max-wait: -1#集群版 jedis: pool: max-active: 8 max-wait: -1 max-idle: 8 min-idle: 0 timeout: 10000 cluster: nodes: - 192.168.100.131:6001 - 192.168.100.131:6002 - 192.168.100.131:6003 - 192.168.100.131:6004 - 192.168.100.131:6005 - 192.168.100.131:6006
不懂redis集群搭建的请看:https://my.oschina.net/shxjinchao/blog/1923715
接下来就是如何使用redis了,这个很简单调用工具类即可
如下代码片段:
@RestControllerpublic class MemberServiceImpl extends BaseApiService implements MemberService { @Autowired private BaseRedisService baseRedisService; @Autowired private MemberMapper memberMapper; @Override public void testRedisSet(String key, String value) { baseRedisService.setString(key,value); }}