服务器之家:专注于服务器技术及软件下载分享
分类导航

Mysql|Sql Server|Oracle|Redis|MongoDB|PostgreSQL|Sqlite|DB2|mariadb|Access|数据库技术|

服务器之家 - 数据库 - Redis - Redis在项目中的使用(JedisPool方式)

Redis在项目中的使用(JedisPool方式)

2022-01-25 17:41HongMaJu Redis

项目操作redis是使用的RedisTemplate方式,另外还可以完全使用JedisPool和Jedis来操作redis,本文给大家介绍Redis在项目中的使用,JedisPool方式,感兴趣的朋友跟随小编一起看看吧

springboot中redis相关配置

1、pom.xml中引入依赖

?
1
2
3
4
5
<dependency>
  <groupid>redis.clients</groupid>
  <artifactid>jedis</artifactid>
  <version>2.9.0</version>
</dependency>

2、springboot的习惯优于配置。也在项目中使用了application.yml文件配置mysql的基本配置项。这里也在application.yml里面配置redis的配置项。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
spring:
  datasource:
        # 驱动配置信息
        url: jdbc:mysql://localhost:3306/spring_boot?useunicode=true&characterencoding=utf8
        username: root
        password: root
        type: com.alibaba.druid.pool.druiddatasource
        driver-class-name: com.mysql.jdbc.driver
 
        # 连接池的配置信息
        filters: stat
        maxactive: 20
        initialsize: 1
        maxwait: 60000
        minidle: 1
        timebetweenevictionrunsmillis: 60000
        minevictableidletimemillis: 300000
        validationquery: select 'x'
        testwhileidle: true
        testonborrow: false
        testonreturn: false
        poolpreparedstatements: true
        maxopenpreparedstatements: 20
  redis:
        host: 127.0.0.1
        port: 6379
        password: pass1234
        pool:
          max-active: 100
          max-idle: 10
          max-wait: 100000
        timeout: 0

springboot中redis相关类

  • 项目操作redis是使用的redistemplate方式,另外还可以完全使用jedispool和jedis来操作redis。整合的内容也是从网上收集整合而来,网上整合的方式和方法非常的多,有使用注解形式的,有使用jackson2jsonredisserializer来序列化和反序列化key value的值等等,很多很多。这里使用的是我认为比较容易理解和掌握的,基于jedispool配置,使用redistemplate来操作redis的方式。

redis单独放在一个包redis里,在包里先创建redisconfig.java文件。

redisconfig.java

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
@configuration
@enableautoconfiguration
public class redisconfig {
 
    @bean
    @configurationproperties(prefix = "spring.redis.pool")
    public jedispoolconfig getredisconfig(){
        jedispoolconfig config = new jedispoolconfig();
        return config;
    }
 
    @bean
    @configurationproperties(prefix = "spring.redis")
    public jedisconnectionfactory getconnectionfactory() {
        jedisconnectionfactory factory = new jedisconnectionfactory();
        factory.setusepool(true);
        jedispoolconfig config = getredisconfig();
        factory.setpoolconfig(config);
        return factory;
    }
 
    @bean
    public redistemplate<?, ?> getredistemplate() {
        jedisconnectionfactory factory = getconnectionfactory();
        redistemplate<?, ?> template = new stringredistemplate(factory);
        return template;
    }
 
}
  • 在包里创建redisservice接口的实现类redisserviceimpl,这个类实现了接口的所有方法。

redisserviceimpl.java

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
@service("redisservice")
public class redisserviceimpl implements redisservice {
 
    @resource
    private redistemplate<string, ?> redistemplate;
 
    @override
    public boolean set(final string key, final string value) {
        boolean result = redistemplate.execute(new rediscallback<boolean>() {
            @override
            public boolean doinredis(redisconnection connection) throws dataaccessexception {
                redisserializer<string> serializer = redistemplate.getstringserializer();
                connection.set(serializer.serialize(key), serializer.serialize(value));
                return true;
            }
        });
        return result;
    }
 
    @override
    public string get(final string key) {
        string result = redistemplate.execute(new rediscallback<string>() {
            @override
            public string doinredis(redisconnection connection) throws dataaccessexception {
                redisserializer<string> serializer = redistemplate.getstringserializer();
                byte[] value = connection.get(serializer.serialize(key));
                return serializer.deserialize(value);
            }
        });
        return result;
    }
 
    @override
    public boolean expire(final string key, long expire) {
        return redistemplate.expire(key, expire, timeunit.seconds);
    }
 
    @override
    public boolean remove(final string key) {
        boolean result = redistemplate.execute(new rediscallback<boolean>() {
            @override
            public boolean doinredis(redisconnection connection) throws dataaccessexception {
                redisserializer<string> serializer = redistemplate.getstringserializer();
                connection.del(key.getbytes());
                return true;
            }
        });
        return result;
    }
}

在这里execute()方法具体的底层没有去研究,只知道这样能实现对于redis数据的操作。
redis保存的数据会在内存和硬盘上存储,所以需要做序列化;这个里面使用的stringredisserializer来做序列化,不过这个方式的泛型指定的是string,只能传string进来。所以项目中采用json字符串做redis的交互。

到此,redis在springboot中的整合已经完毕,下面就来测试使用一下。

5. springboot项目中使用redis

在这里就直接使用springboot项目中自带的单元测试类springbootapplicationtests进行测试。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
@runwith(springrunner.class)
@springboottest
public class springbootapplicationtests {
 
    private jsonobject json = new jsonobject();
 
    @autowired
    private redisservice redisservice;
 
    @test
    public void contextloads() throws exception {
    }
 
 
    /**
     * 插入字符串
     */
    @test
    public void setstring() {
        redisservice.set("redis_string_test", "springboot redis test");
    }
 
    /**
     * 获取字符串
     */
    @test
    public void getstring() {
        string result = redisservice.get("redis_string_test");
        system.out.println(result);
    }
 
    /**
     * 插入对象
     */
    @test
    public void setobject() {
        person person = new person("person", "male");
        redisservice.set("redis_obj_test", json.tojsonstring(person));
    }
 
    /**
     * 获取对象
     */
    @test
    public void getobject() {
        string result = redisservice.get("redis_obj_test");
        person person = json.parseobject(result, person.class);
        system.out.println(json.tojsonstring(person));
    }
 
    /**
     * 插入对象list
     */
    @test
    public void setlist() {
        person person1 = new person("person1", "male");
        person person2 = new person("person2", "female");
        person person3 = new person("person3", "male");
        list<person> list = new arraylist<>();
        list.add(person1);
        list.add(person2);
        list.add(person3);
        redisservice.set("redis_list_test", json.tojsonstring(list));
    }
 
    /**
     * 获取list
     */
    @test
    public void getlist() {
        string result = redisservice.get("redis_list_test");
        list<string> list = json.parsearray(result, string.class);
        system.out.println(list);
    }
 
    @test
    public void remove() {
        redisservice.remove("redis_test");
    }
 
}
 
class person {
    private string name;
    private string sex;
 
    public person() {
 
    }
 
    public person(string name, string sex) {
        this.name = name;
        this.sex = sex;
    }
 
    public string getname() {
        return name;
    }
 
    public void setname(string name) {
        this.name = name;
    }
 
    public string getsex() {
        return sex;
    }
 
    public void setsex(string sex) {
        this.sex = sex;
    }
}

在这里先是用@autowired注解把redisservice注入进来,然后由于是使用json字符串进行交互,所以引入fastjson的jsonobject类。然后为了方便,直接在这个测试类里面加了一个person的内部类。

一共测试了:对于string类型的存取,对于object类型的存取,对于list类型的存取,其实本质都是转成了json字符串。还有就是根据key来执行remove操作。

获取字符串:

Redis在项目中的使用(JedisPool方式)

获取对象:

Redis在项目中的使用(JedisPool方式)

获取list:

Redis在项目中的使用(JedisPool方式)

redis管理客户端数据:

Redis在项目中的使用(JedisPool方式)

到此,测试完成,对于常用的一些数据类型的转换存取操作也基本调试通过。所以本文对于springboot整合redis到此结束。

到此这篇关于redis在项目中的使用(jedispool方式)的文章就介绍到这了,更多相关redis项目中使用内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://www.cnblogs.com/hongmaju/p/15726547.html

延伸 · 阅读

精彩推荐
  • Redisredis启动,停止,及端口占用处理方法

    redis启动,停止,及端口占用处理方法

    今天小编就为大家分享一篇redis启动,停止,及端口占用处理方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧 ...

    澄海单挑狂5152019-11-14
  • Redis聊一聊Redis与MySQL双写一致性如何保证

    聊一聊Redis与MySQL双写一致性如何保证

    一致性就是数据保持一致,在分布式系统中,可以理解为多个节点中数据的值是一致的。本文给大家分享Redis与MySQL双写一致性该如何保证,感兴趣的朋友一...

    mind_programmonkey6432021-08-12
  • RedisRedis分布式锁升级版RedLock及SpringBoot实现方法

    Redis分布式锁升级版RedLock及SpringBoot实现方法

    这篇文章主要介绍了Redis分布式锁升级版RedLock及SpringBoot实现,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以...

    等不到的口琴7802021-07-25
  • RedisRedis数据结构之链表与字典的使用

    Redis数据结构之链表与字典的使用

    这篇文章主要介绍了Redis数据结构之链表与字典的使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友...

    白泽来了4052021-08-03
  • RedisLinux Redis 的安装步骤详解

    Linux Redis 的安装步骤详解

    这篇文章主要介绍了 Linux Redis 的安装步骤详解的相关资料,希望大家通过本文能掌握如何安装Redis,需要的朋友可以参考下 ...

    carl-zhao3822019-11-08
  • Redis在ssm项目中使用redis缓存查询数据的方法

    在ssm项目中使用redis缓存查询数据的方法

    本文主要简单的使用Java代码进行redis缓存,即在查询的时候先在service层从redis缓存中获取数据。如果大家对在ssm项目中使用redis缓存查询数据的相关知识感...

    caychen8962019-11-12
  • RedisRedis存取序列化与反序列化性能问题详解

    Redis存取序列化与反序列化性能问题详解

    这篇文章主要给大家介绍了关于Redis存取序列化与反序列化性能问题的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参...

    这名字已经存在9742021-02-24
  • Redis就这?Redis持久化策略——AOF

    就这?Redis持久化策略——AOF

    今天为大家介绍Redis的另一种持久化策略——AOF。注意:AOF文件只会记录Redis的写操作命令,因为读命令对数据的恢复没有任何意义...

    头发茂密的刘叔4052021-12-14