application.properties
加入redis账户配置以及redis连接池配置,本地默认没有密码 : localhost:6379
#thymeleafspring.thymeleaf.prefix=classpath:/templates/spring.thymeleaf.suffix=.htmlspring.thymeleaf.cache=falsespring.thymeleaf.content-type=text/htmlspring.thymeleaf.enabled=truespring.thymeleaf.encoding=UTF-8spring.thymeleaf.mode=HTML5# mybatismybatis.type-aliases-package=com.fengqiuhua.pro.entitymybatis.configuration.map-underscore-to-camel-case=truemybatis.configuration.default-fetch-size=100mybatis.configuration.default-statement-timeout=3000mybatis.mapperLocations = classpath:com/fengqiuhua/pro/mapper/xml/*.xml# druidspring.datasource.url=jdbc:mysql://mysql-test.agilenaas.net:3307/company?useOldAliasMetadataBehavior=true&useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghaispring.datasource.username=rootspring.datasource.password=ags@2020spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driverspring.datasource.type=com.alibaba.druid.pool.DruidDataSourcespring.datasource.filters=statspring.datasource.maxActive=1000spring.datasource.initialSize=100spring.datasource.maxWait=60000spring.datasource.minIdle=500spring.datasource.timeBetweenEvictionRunsMillis=60000spring.datasource.minEvictableIdleTimeMillis=300000spring.datasource.validationQuery=select 'x'spring.datasource.testWhileIdle=truespring.datasource.testOnBorrow=falsespring.datasource.testOnReturn=falsespring.datasource.poolPreparedStatements=truespring.datasource.maxOpenPreparedStatements=20#redisredis.host=localhostredis.port=6379redis.timeout=10#redis.password=123456redis.poolMaxTotal=1000redis.poolMaxIdle=500redis.poolMaxWait=500
将配置参数封装成到类RedisConfig
ConfigurationProperties注解在springboot启动时会扫描配置文件中以redis为前缀的参数,并将值注入到类变量中
@Component@ConfigurationProperties(prefix="redis")public class RedisConfig {private String host;private int port;private int timeout;//秒private String password;private int poolMaxTotal;private int poolMaxIdle;private int poolMaxWait;//秒public String getHost() {return host;}public void setHost(String host) {this.host = host;}public int getPort() {return port;}public void setPort(int port) {this.port = port;}public int getTimeout() {return timeout;}public void setTimeout(int timeout) {this.timeout = timeout;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public int getPoolMaxTotal() {return poolMaxTotal;}public void setPoolMaxTotal(int poolMaxTotal) {this.poolMaxTotal = poolMaxTotal;}public int getPoolMaxIdle() {return poolMaxIdle;}public void setPoolMaxIdle(int poolMaxIdle) {this.poolMaxIdle = poolMaxIdle;}public int getPoolMaxWait() {return poolMaxWait;}public void setPoolMaxWait(int poolMaxWait) {this.poolMaxWait = poolMaxWait;}}
自定义连接池JedisPool
@Componentpublic class RedisPoolFactory {@AutowiredRedisConfig redisConfig;@Beanpublic JedisPool JedisPoolFactory() {JedisPoolConfig poolConfig = new JedisPoolConfig();poolConfig.setMaxIdle(redisConfig.getPoolMaxIdle());poolConfig.setMaxTotal(redisConfig.getPoolMaxTotal());poolConfig.setMaxWaitMillis(redisConfig.getPoolMaxWait() * 1000);JedisPool jp = new JedisPool(poolConfig, redisConfig.getHost(), redisConfig.getPort(),redisConfig.getTimeout()*1000, redisConfig.getPassword(), 0);return jp;}}
编写redis服务类 RedisService
可以通过JedisPool获取到jedis客户端了,随后就可以set ,get 了。
这种方式优于通过RedisTemplate模板 直接 set get。
@Servicepublic class RedisService {@AutowiredJedisPool jedisPool;/*** 获取当个对象* */public <T> T get(KeyPrefix prefix, String key, Class<T> clazz) {Jedis jedis = null;try {jedis = jedisPool.getResource();//生成真正的keyString realKey = prefix.getPrefix() + key;String str = jedis.get(realKey);T t = stringToBean(str, clazz);return t;}finally {returnToPool(jedis);}}/*** 设置对象* */public <T> boolean set(KeyPrefix prefix, String key, T value) {Jedis jedis = null;try {jedis = jedisPool.getResource();String str = beanToString(value);if(str == null || str.length() <= 0) {return false;}//生成真正的keyString realKey = prefix.getPrefix() + key;int seconds = prefix.expireSeconds();if(seconds <= 0) {jedis.set(realKey, str);}else {jedis.setex(realKey, seconds, str);}return true;}finally {returnToPool(jedis);}}/*** 判断key是否存在* */public <T> boolean exists(KeyPrefix prefix, String key) {Jedis jedis = null;try {jedis = jedisPool.getResource();//生成真正的keyString realKey = prefix.getPrefix() + key;return jedis.exists(realKey);}finally {returnToPool(jedis);}}/*** 删除* */public boolean delete(KeyPrefix prefix, String key) {Jedis jedis = null;try {jedis = jedisPool.getResource();//生成真正的keyString realKey = prefix.getPrefix() + key;long ret = jedis.del(realKey);return ret > 0;}finally {returnToPool(jedis);}}/*** 增加值* */public <T> Long incr(KeyPrefix prefix, String key) {Jedis jedis = null;try {jedis = jedisPool.getResource();//生成真正的keyString realKey = prefix.getPrefix() + key;return jedis.incr(realKey);}finally {returnToPool(jedis);}}/*** 减少值* */public <T> Long decr(KeyPrefix prefix, String key) {Jedis jedis = null;try {jedis = jedisPool.getResource();//生成真正的keyString realKey = prefix.getPrefix() + key;return jedis.decr(realKey);}finally {returnToPool(jedis);}}public boolean delete(KeyPrefix prefix) {if(prefix == null) {return false;}List<String> keys = scanKeys(prefix.getPrefix());if(keys==null || keys.size() <= 0) {return true;}Jedis jedis = null;try {jedis = jedisPool.getResource();jedis.del(keys.toArray(new String[0]));return true;} catch (final Exception e) {e.printStackTrace();return false;} finally {if(jedis != null) {jedis.close();}}}public List<String> scanKeys(String key) {Jedis jedis = null;try {jedis = jedisPool.getResource();List<String> keys = new ArrayList<String>();String cursor = "0";ScanParams sp = new ScanParams();sp.match("*"+key+"*");sp.count(100);do{ScanResult<String> ret = jedis.scan(cursor, sp);List<String> result = ret.getResult();if(result!=null && result.size() > 0){keys.addAll(result);}//再处理cursorcursor = ret.getCursor();}while(!cursor.equals("0"));return keys;} finally {if (jedis != null) {jedis.close();}}}public static <T> String beanToString(T value) {if(value == null) {return null;}Class<?> clazz = value.getClass();if(clazz == int.class || clazz == Integer.class) {return ""+value;}else if(clazz == String.class) {return (String)value;}else if(clazz == long.class || clazz == Long.class) {return ""+value;}else {return JSON.toJSONString(value);}}@SuppressWarnings("unchecked")public static <T> T stringToBean(String str, Class<T> clazz) {if(str == null || str.length() <= 0 || clazz == null) {return null;}if(clazz == int.class || clazz == Integer.class) {return (T) Integer.valueOf(str);}else if(clazz == String.class) {return (T)str;}else if(clazz == long.class || clazz == Long.class) {return (T) Long.valueOf(str);}else {return JSON.toJavaObject(JSON.parseObject(str), clazz);}}private void returnToPool(Jedis jedis) {if(jedis != null) {jedis.close();}}}
controller测试redis
先不用redis service。
直接用从pool中获取一个jedis ,然后进行set,get。
@AutowiredJedisPool jedisPool;@GetMapping("/setRedis")@ResponseBodypublic Result<Object> setRedis(){Jedis resource = jedisPool.getResource();resource.set("test","1111");return Result.success(resource.get("test"));}
