application.properties


加入redis账户配置以及redis连接池配置,本地默认没有密码 : localhost:6379

  1. #thymeleaf
  2. spring.thymeleaf.prefix=classpath:/templates/
  3. spring.thymeleaf.suffix=.html
  4. spring.thymeleaf.cache=false
  5. spring.thymeleaf.content-type=text/html
  6. spring.thymeleaf.enabled=true
  7. spring.thymeleaf.encoding=UTF-8
  8. spring.thymeleaf.mode=HTML5
  9. # mybatis
  10. mybatis.type-aliases-package=com.fengqiuhua.pro.entity
  11. mybatis.configuration.map-underscore-to-camel-case=true
  12. mybatis.configuration.default-fetch-size=100
  13. mybatis.configuration.default-statement-timeout=3000
  14. mybatis.mapperLocations = classpath:com/fengqiuhua/pro/mapper/xml/*.xml
  15. # druid
  16. spring.datasource.url=jdbc:mysql://mysql-test.agilenaas.net:3307/company?useOldAliasMetadataBehavior=true&useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai
  17. spring.datasource.username=root
  18. spring.datasource.password=ags@2020
  19. spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
  20. spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
  21. spring.datasource.filters=stat
  22. spring.datasource.maxActive=1000
  23. spring.datasource.initialSize=100
  24. spring.datasource.maxWait=60000
  25. spring.datasource.minIdle=500
  26. spring.datasource.timeBetweenEvictionRunsMillis=60000
  27. spring.datasource.minEvictableIdleTimeMillis=300000
  28. spring.datasource.validationQuery=select 'x'
  29. spring.datasource.testWhileIdle=true
  30. spring.datasource.testOnBorrow=false
  31. spring.datasource.testOnReturn=false
  32. spring.datasource.poolPreparedStatements=true
  33. spring.datasource.maxOpenPreparedStatements=20
  34. #redis
  35. redis.host=localhost
  36. redis.port=6379
  37. redis.timeout=10
  38. #redis.password=123456
  39. redis.poolMaxTotal=1000
  40. redis.poolMaxIdle=500
  41. redis.poolMaxWait=500

将配置参数封装成到类RedisConfig


ConfigurationProperties注解在springboot启动时会扫描配置文件中以redis为前缀的参数,并将值注入到类变量中

  1. @Component
  2. @ConfigurationProperties(prefix="redis")
  3. public class RedisConfig {
  4. private String host;
  5. private int port;
  6. private int timeout;//秒
  7. private String password;
  8. private int poolMaxTotal;
  9. private int poolMaxIdle;
  10. private int poolMaxWait;//秒
  11. public String getHost() {
  12. return host;
  13. }
  14. public void setHost(String host) {
  15. this.host = host;
  16. }
  17. public int getPort() {
  18. return port;
  19. }
  20. public void setPort(int port) {
  21. this.port = port;
  22. }
  23. public int getTimeout() {
  24. return timeout;
  25. }
  26. public void setTimeout(int timeout) {
  27. this.timeout = timeout;
  28. }
  29. public String getPassword() {
  30. return password;
  31. }
  32. public void setPassword(String password) {
  33. this.password = password;
  34. }
  35. public int getPoolMaxTotal() {
  36. return poolMaxTotal;
  37. }
  38. public void setPoolMaxTotal(int poolMaxTotal) {
  39. this.poolMaxTotal = poolMaxTotal;
  40. }
  41. public int getPoolMaxIdle() {
  42. return poolMaxIdle;
  43. }
  44. public void setPoolMaxIdle(int poolMaxIdle) {
  45. this.poolMaxIdle = poolMaxIdle;
  46. }
  47. public int getPoolMaxWait() {
  48. return poolMaxWait;
  49. }
  50. public void setPoolMaxWait(int poolMaxWait) {
  51. this.poolMaxWait = poolMaxWait;
  52. }
  53. }

自定义连接池JedisPool


  1. @Component
  2. public class RedisPoolFactory {
  3. @Autowired
  4. RedisConfig redisConfig;
  5. @Bean
  6. public JedisPool JedisPoolFactory() {
  7. JedisPoolConfig poolConfig = new JedisPoolConfig();
  8. poolConfig.setMaxIdle(redisConfig.getPoolMaxIdle());
  9. poolConfig.setMaxTotal(redisConfig.getPoolMaxTotal());
  10. poolConfig.setMaxWaitMillis(redisConfig.getPoolMaxWait() * 1000);
  11. JedisPool jp = new JedisPool(poolConfig, redisConfig.getHost(), redisConfig.getPort(),
  12. redisConfig.getTimeout()*1000, redisConfig.getPassword(), 0);
  13. return jp;
  14. }
  15. }

编写redis服务类 RedisService


可以通过JedisPool获取到jedis客户端了,随后就可以set ,get 了。

这种方式优于通过RedisTemplate模板 直接 set get。

  1. @Service
  2. public class RedisService {
  3. @Autowired
  4. JedisPool jedisPool;
  5. /**
  6. * 获取当个对象
  7. * */
  8. public <T> T get(KeyPrefix prefix, String key, Class<T> clazz) {
  9. Jedis jedis = null;
  10. try {
  11. jedis = jedisPool.getResource();
  12. //生成真正的key
  13. String realKey = prefix.getPrefix() + key;
  14. String str = jedis.get(realKey);
  15. T t = stringToBean(str, clazz);
  16. return t;
  17. }finally {
  18. returnToPool(jedis);
  19. }
  20. }
  21. /**
  22. * 设置对象
  23. * */
  24. public <T> boolean set(KeyPrefix prefix, String key, T value) {
  25. Jedis jedis = null;
  26. try {
  27. jedis = jedisPool.getResource();
  28. String str = beanToString(value);
  29. if(str == null || str.length() <= 0) {
  30. return false;
  31. }
  32. //生成真正的key
  33. String realKey = prefix.getPrefix() + key;
  34. int seconds = prefix.expireSeconds();
  35. if(seconds <= 0) {
  36. jedis.set(realKey, str);
  37. }else {
  38. jedis.setex(realKey, seconds, str);
  39. }
  40. return true;
  41. }finally {
  42. returnToPool(jedis);
  43. }
  44. }
  45. /**
  46. * 判断key是否存在
  47. * */
  48. public <T> boolean exists(KeyPrefix prefix, String key) {
  49. Jedis jedis = null;
  50. try {
  51. jedis = jedisPool.getResource();
  52. //生成真正的key
  53. String realKey = prefix.getPrefix() + key;
  54. return jedis.exists(realKey);
  55. }finally {
  56. returnToPool(jedis);
  57. }
  58. }
  59. /**
  60. * 删除
  61. * */
  62. public boolean delete(KeyPrefix prefix, String key) {
  63. Jedis jedis = null;
  64. try {
  65. jedis = jedisPool.getResource();
  66. //生成真正的key
  67. String realKey = prefix.getPrefix() + key;
  68. long ret = jedis.del(realKey);
  69. return ret > 0;
  70. }finally {
  71. returnToPool(jedis);
  72. }
  73. }
  74. /**
  75. * 增加值
  76. * */
  77. public <T> Long incr(KeyPrefix prefix, String key) {
  78. Jedis jedis = null;
  79. try {
  80. jedis = jedisPool.getResource();
  81. //生成真正的key
  82. String realKey = prefix.getPrefix() + key;
  83. return jedis.incr(realKey);
  84. }finally {
  85. returnToPool(jedis);
  86. }
  87. }
  88. /**
  89. * 减少值
  90. * */
  91. public <T> Long decr(KeyPrefix prefix, String key) {
  92. Jedis jedis = null;
  93. try {
  94. jedis = jedisPool.getResource();
  95. //生成真正的key
  96. String realKey = prefix.getPrefix() + key;
  97. return jedis.decr(realKey);
  98. }finally {
  99. returnToPool(jedis);
  100. }
  101. }
  102. public boolean delete(KeyPrefix prefix) {
  103. if(prefix == null) {
  104. return false;
  105. }
  106. List<String> keys = scanKeys(prefix.getPrefix());
  107. if(keys==null || keys.size() <= 0) {
  108. return true;
  109. }
  110. Jedis jedis = null;
  111. try {
  112. jedis = jedisPool.getResource();
  113. jedis.del(keys.toArray(new String[0]));
  114. return true;
  115. } catch (final Exception e) {
  116. e.printStackTrace();
  117. return false;
  118. } finally {
  119. if(jedis != null) {
  120. jedis.close();
  121. }
  122. }
  123. }
  124. public List<String> scanKeys(String key) {
  125. Jedis jedis = null;
  126. try {
  127. jedis = jedisPool.getResource();
  128. List<String> keys = new ArrayList<String>();
  129. String cursor = "0";
  130. ScanParams sp = new ScanParams();
  131. sp.match("*"+key+"*");
  132. sp.count(100);
  133. do{
  134. ScanResult<String> ret = jedis.scan(cursor, sp);
  135. List<String> result = ret.getResult();
  136. if(result!=null && result.size() > 0){
  137. keys.addAll(result);
  138. }
  139. //再处理cursor
  140. cursor = ret.getCursor();
  141. }while(!cursor.equals("0"));
  142. return keys;
  143. } finally {
  144. if (jedis != null) {
  145. jedis.close();
  146. }
  147. }
  148. }
  149. public static <T> String beanToString(T value) {
  150. if(value == null) {
  151. return null;
  152. }
  153. Class<?> clazz = value.getClass();
  154. if(clazz == int.class || clazz == Integer.class) {
  155. return ""+value;
  156. }else if(clazz == String.class) {
  157. return (String)value;
  158. }else if(clazz == long.class || clazz == Long.class) {
  159. return ""+value;
  160. }else {
  161. return JSON.toJSONString(value);
  162. }
  163. }
  164. @SuppressWarnings("unchecked")
  165. public static <T> T stringToBean(String str, Class<T> clazz) {
  166. if(str == null || str.length() <= 0 || clazz == null) {
  167. return null;
  168. }
  169. if(clazz == int.class || clazz == Integer.class) {
  170. return (T) Integer.valueOf(str);
  171. }else if(clazz == String.class) {
  172. return (T)str;
  173. }else if(clazz == long.class || clazz == Long.class) {
  174. return (T) Long.valueOf(str);
  175. }else {
  176. return JSON.toJavaObject(JSON.parseObject(str), clazz);
  177. }
  178. }
  179. private void returnToPool(Jedis jedis) {
  180. if(jedis != null) {
  181. jedis.close();
  182. }
  183. }
  184. }

controller测试redis


先不用redis service。
直接用从pool中获取一个jedis ,然后进行set,get。

  1. @Autowired
  2. JedisPool jedisPool;
  3. @GetMapping("/setRedis")
  4. @ResponseBody
  5. public Result<Object> setRedis(){
  6. Jedis resource = jedisPool.getResource();
  7. resource.set("test","1111");
  8. return Result.success(resource.get("test"));
  9. }