上一篇笔记Reddis集成,操作Redis使用的是RedisTemplate,但实际中还是有一大部分人习惯使用JedisPool和Jedis来操作Redis, 下面使用Jedis集成示例。

修改RedisConfig类如下:

  1. package com.vic.config;
  2. import org.apache.log4j.Logger;
  3. import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
  4. import org.springframework.boot.context.properties.ConfigurationProperties;
  5. import org.springframework.context.annotation.Bean;
  6. import org.springframework.context.annotation.Configuration;
  7. import redis.clients.jedis.JedisPool;
  8. import redis.clients.jedis.JedisPoolConfig;
  9. /**
  10. *
  11. * @author vic
  12. * @desc redis config bean
  13. *
  14. */
  15. @Configuration
  16. @EnableAutoConfiguration
  17. @ConfigurationProperties(prefix = "spring.redis", locations = "classpath:application.properties")
  18. public class RedisConfig {
  19. private static Logger logger = Logger.getLogger(RedisConfig.class);
  20. private String hostName;
  21. private int port;
  22. private String password;
  23. private int timeout;
  24. @Bean
  25. public JedisPoolConfig getRedisConfig(){
  26. JedisPoolConfig config = new JedisPoolConfig();
  27. return config;
  28. }
  29. @Bean
  30. public JedisPool getJedisPool(){
  31. JedisPoolConfig config = getRedisConfig();
  32. JedisPool pool = new JedisPool(config,hostName,port,timeout,password);
  33. logger.info("init JredisPool ...");
  34. return pool;
  35. }
  36. public String getHostName() {
  37. return hostName;
  38. }
  39. public void setHostName(String hostName) {
  40. this.hostName = hostName;
  41. }
  42. public int getPort() {
  43. return port;
  44. }
  45. public void setPort(int port) {
  46. this.port = port;
  47. }
  48. public String getPassword() {
  49. return password;
  50. }
  51. public void setPassword(String password) {
  52. this.password = password;
  53. }
  54. public int getTimeout() {
  55. return timeout;
  56. }
  57. public void setTimeout(int timeout) {
  58. this.timeout = timeout;
  59. }
  60. }

因为JedisPool实例化对象,是将host,password等参数通过构造传入,所以在这里将整个RedisConfig定义为一个配置类,定义host,password等配置属性,通过spring boot属性文件自动注入。

接下来看看Service中如何使用:

修改IRedisService接口:

  1. /**
  2. *
  3. * @author vic
  4. * @desc redis service
  5. */
  6. public interface IRedisService {
  7. public Jedis getResource();
  8. public void returnResource(Jedis jedis);
  9. public void set(String key, String value);
  10. public String get(String key);
  11. }

RedisService实现类代码:

  1. package com.vic.service.impl;
  2. import org.apache.log4j.Logger;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.stereotype.Service;
  5. import com.vic.service.IRedisService;
  6. import redis.clients.jedis.Jedis;
  7. import redis.clients.jedis.JedisPool;
  8. /**
  9. *
  10. * @author vic
  11. * @desc resdis service
  12. *
  13. */
  14. @Service
  15. public class RedisServiceImpl implements IRedisService {
  16. private static Logger logger = Logger.getLogger(RedisServiceImpl.class);
  17. @Autowired
  18. private JedisPool jedisPool;
  19. @Override
  20. public Jedis getResource() {
  21. return jedisPool.getResource();
  22. }
  23. @SuppressWarnings("deprecation")
  24. @Override
  25. public void returnResource(Jedis jedis) {
  26. if(jedis != null){
  27. jedisPool.returnResourceObject(jedis);
  28. }
  29. }
  30. @Override
  31. public void set(String key, String value) {
  32. Jedis jedis=null;
  33. try{
  34. jedis = getResource();
  35. jedis.set(key, value);
  36. logger.info("Redis set success - " + key + ", value:" + value);
  37. } catch (Exception e) {
  38. e.printStackTrace();
  39. logger.error("Redis set error: "+ e.getMessage() +" - " + key + ", value:" + value);
  40. }finally{
  41. returnResource(jedis);
  42. }
  43. }
  44. @Override
  45. public String get(String key) {
  46. String result = null;
  47. Jedis jedis=null;
  48. try{
  49. jedis = getResource();
  50. result = jedis.get(key);
  51. logger.info("Redis get success - " + key + ", value:" + result);
  52. } catch (Exception e) {
  53. e.printStackTrace();
  54. logger.error("Redis set error: "+ e.getMessage() +" - " + key + ", value:" + result);
  55. }finally{
  56. returnResource(jedis);
  57. }
  58. return result;
  59. }
  60. }

JedisPool对象使用自动注入,手动获取Jedis对象进行Redis操作,ExampleController进行测试:

  1. @RequestMapping("/redis/set")
  2. public ResponseModal redisSet(@RequestParam("value")String value){
  3. redisService.set("name", value);
  4. return new ResponseModal(200, true, "success", null);
  5. }
  6. @RequestMapping("/redis/get")
  7. public ResponseModal redisGet(){
  8. String name = redisService.get("name");
  9. return new ResponseModal(200, true,"success",name);
  10. }

测试URL:http://localhost:8080/redis/set?value=vic  响应结果:

{"code":200,"success":true,"message":"success","response":null}

测试URL:http://localhost:8080/redis/get   响应结果:

{"code":200,"success":true,"message":"success","response":"vic"}

点击下载示例

 

spring boot 自学笔记(四) Redis集成—Jedis的更多相关文章

  1. Spring Boot(十一)Redis集成从Docker安装到分布式Session共享

    一.简介 Redis是一个开源的使用ANSI C语言编写.支持网络.可基于内存亦可持久化的日志型.Key-Value数据库,并提供多种语言的API,Redis也是技术领域使用最为广泛的存储中间件,它是 ...

  2. Spring Boot 学习笔记--整合Redis

    1.新建Spring Boot项目 添加spring-boot-starter-data-redis依赖 <dependency> <groupId>org.springfra ...

  3. Spring Boot 2.x 整合 Redis最佳实践

    一.前言 在前面的几篇文章中简单的总结了一下Redis相关的知识.本章主要讲解一下 Spring Boot 2.0 整合 Redis.Jedis 和 Lettuce 是 Java 操作 Redis 的 ...

  4. Spring Boot 学习笔记(六) 整合 RESTful 参数传递

    Spring Boot 学习笔记 源码地址 Spring Boot 学习笔记(一) hello world Spring Boot 学习笔记(二) 整合 log4j2 Spring Boot 学习笔记 ...

  5. spring boot / cloud (十四) 微服务间远程服务调用的认证和鉴权的思考和设计,以及restFul风格的url匹配拦截方法

    spring boot / cloud (十四) 微服务间远程服务调用的认证和鉴权的思考和设计,以及restFul风格的url匹配拦截方法 前言 本篇接着<spring boot / cloud ...

  6. Spring Boot 2.0 图文教程 | 集成邮件发送功能

    文章首发自个人微信公众号: 小哈学Java 个人网站: https://www.exception.site/springboot/spring-boots-send-mail 大家好,后续会间断地奉 ...

  7. Spring Boot 2.x整合Redis

    最近在学习Spring Boot 2.x整合Redis,在这里和大家分享一下,希望对大家有帮助. Redis是什么 Redis 是开源免费高性能的key-value数据库.有以下的优势(源于Redis ...

  8. Spring Boot 2.X 如何快速集成单元测试?

    本文将详细介绍下使用Spring Boot 2.X 集成单元测试,对API(Controller)测试的过程. 一.实现原理 使用MockMvc发起请求,然后执行API中相应的代码,在执行的过程中使m ...

  9. Spring Boot学习笔记2——基本使用之最佳实践[z]

    前言 在上一篇文章Spring Boot 学习笔记1——初体验之3分钟启动你的Web应用已经对Spring Boot的基本体系与基本使用进行了学习,本文主要目的是更加进一步的来说明对于Spring B ...

随机推荐

  1. Android开发之探秘蓝牙隐藏API

    这次讲得深入些,探讨下蓝牙方面的隐藏API.用过Android系统设置(Setting)的人都知道蓝牙搜索之后可以建立配对和解除配对,但是这两项功能的函数没有在SDK中给出,那么如何去使用这两项功能呢 ...

  2. PostgreSQL安装详细步骤(windows)[转]

    PostgreSQL安装: 一.windows下安装过程 安装介质:postgresql-9.1.3-1-windows.exe(46M),安装过程非常简单,过程如下: 1.开始安装: 2.选择程序安 ...

  3. Linux 分区注意事项

    必须分区: 1)/(根分区) 2)/swap(交换分区,当内存不超过4G时,建议swap大小为内存2倍,若超过4G,建议交换分区跟内存一样大) 推荐分区 /boot(启动分区,单独分区,最新200M)

  4. 进程间通信机制(管道、信号、共享内存/信号量/消息队列)、线程间通信机制(互斥锁、条件变量、posix匿名信号量)

    注:本分类下文章大多整理自<深入分析linux内核源代码>一书,另有参考其他一些资料如<linux内核完全剖析>.<linux c 编程一站式学习>等,只是为了更好 ...

  5. struts2 页面标签或ognl表达式取值--未完待续

    一.加#号取值和不加#号取值的解说 1.s:property 标签——value属性使用事项 1)涉及问题:取值时什么时候该加#,什么时候不加? 2)介绍 <s:property value=& ...

  6. 【转】在ASP.NET应用启动的时候初始化的几种方法

    ASP.NET 4.0 之前,有两种方法:通过Global.asax 中的 Application_Start 事件启动,或者通过定义在 App_Code 文件夹中任意类中的AppInitialize ...

  7. QWidget子窗口中setStyleSheet无效,解决方法

    继承 QWidget setStyleSheet无效,解决方法. 发现 继承自QWidget的自定义类 ,使用setStyleSheet无效, 如果删除头文件中的 Q_OBJECT,setStyleS ...

  8. [学习笔记]Spring依赖注入

    依赖: 典型的企业应用程序不可能由单个对象(在spring中,也可称之bean)组成,再简单的应用也是由几个对象相互配合工作的,这一章主要介绍bean的定义以及bean之间的相互协作. 依赖注入: s ...

  9. 关于haproxy负载均衡的算法整理

    目前haproxy支持的负载均衡算法有如下8种: 1:roudrobin 表示简单的轮询,每个服务器根据权重轮流使用,在服务器的处理时间平均分配的情况下这是最流畅和公平的算法.该算法是动态的,对于实例 ...

  10. angular学习笔记(二十二)-$http.post

    基本语法: $http.post('url',{},{}).success(function(data,status,headers,config){ }).error(function(data,s ...