一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術|正則表達式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務器之家 - 編程語言 - Java教程 - Spring集成Redis詳解代碼示例

Spring集成Redis詳解代碼示例

2021-02-05 12:17yangkang029 Java教程

這篇文章主要介紹了Spring集成Redis詳解代碼示例,介紹了Eclipse工程結構,POM依賴,Spring配置,Redis配置信息以及Java代碼等相關內容,具有一定參考價值,需要的朋友可以了解下。

本文章從頭開始介紹spring集成redis的示例。

eclipse工程結構

如下圖為我的示例工程的結構圖,采用maven構建。其中需要集成spring,因此需要beans.xml文件配置spring的依賴注入,redis.properties配置連接服務器的配置信息。

Spring集成Redis詳解代碼示例

其中工程中beans.xml和redis.properties文件直接放在了根目錄,有需要的讀者可以放到resource目錄中。

pom依賴

如下為示例pom依賴,spring集成redis需要依賴的包為:jedis包,spring-context模塊及依賴的包,spring-data-redis模塊包,spring-test包用于junit測試,pom.xml文件內容如下:

?
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
<project xmlns="https://maven.apache.org/pom/4.0.0" xmlns:xsi="https://www.w3.org/2001/xmlschema-instance" xsi:schemalocation="https://maven.apache.org/pom/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelversion>4.0.0</modelversion>
 
  <groupid>com.test</groupid>
  javatest</artifactid>
  <version>0.0.1-snapshot</version>
  <packaging>jar</packaging>
 
  <name>javatest</name>
  <url>https://maven.apache.org</url>
 
  <properties>
    <project.build.sourceencoding>utf-8</project.build.sourceencoding>
  </properties>
 
  <dependencies>
    <dependency>
      <groupid>junit</groupid>
      junit</artifactid>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupid>redis.clients</groupid>
      jedis</artifactid>
      <version>2.5.1</version>
    </dependency>
    <dependency>
      <groupid>org.springframework</groupid>
      spring-context</artifactid>
      <version>4.2.6.release</version>
      <scope>runtime</scope>
    </dependency>
    <dependency>
      <groupid>org.springframework</groupid>
      spring-test</artifactid>
      <version>4.2.6.release</version>
      <scope>runtime</scope>
    </dependency>
    <dependency>
      <groupid>org.springframework.data</groupid>
      spring-data-redis</artifactid>
      <version>1.7.2.release</version>
    </dependency>
  </dependencies>
</project>

spring配置

spring配置文件beans.xml的配置如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<!--?xml version="1.0" encoding="utf-8"?-->
<beans xmlns="https://www.springframework.org/schema/beans" xmlns:aop="https://www.springframework.org/schema/aop" xmlns:context="https://www.springframework.org/schema/context" xmlns:jee="https://www.springframework.org/schema/jee" xmlns:p="https://www.springframework.org/schema/p" xmlns:tx="https://www.springframework.org/schema/tx" xmlns:xsi="https://www.w3.org/2001/xmlschema-instance" xsi:schemalocation="
      https://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
      https://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
  <!-- 加載classpath下的redis配置文件 -->
  <context:property-placeholder location="classpath:redis.properties">
 
  <bean class="redis.clients.jedis.jedispoolconfig" id="poolconfig">
    <property name="maxidle" value="${redis.maxidle}">
    <property name="testonborrow" value="${redis.testonborrow}">
  </property></property></bean>
 
  <bean class="org.springframework.data.redis.connection.jedis.jedisconnectionfactory" id="connectionfactory" p:host-name="${redis.host}" p:password="${redis.pass}" p:pool-config-ref="poolconfig" p:port="${redis.port}">
 
  <!-- spring提供的模板類 -->
  <bean class="org.springframework.data.redis.core.stringredistemplate" id="redistemplate">
    <property name="connectionfactory" ref="connectionfactory">
  </property></bean>
 
  <bean class="com.redis.test.userdao" id="userdao">
    <property name="redistemplate" ref="redistemplate">
  </property></bean>
 
</bean></context:property-placeholder></beans>

在beans.xml配置文件中,需要先加載redis.properties文件。

redis配置信息

redis的配置信息在redis.properties文件中配置:

?
1
2
3
4
5
6
7
# redis地址和端口和連接密碼
redis.host=localhost
redis.port=6379
redis.pass=
 
redis.maxidle=300
redis.testonborrow=true

此示例,連接redis服務器時沒有設置連接密碼,因此不用填值。

java代碼

user.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
package com.redis.test;
import java.io.serializable;
public class user implements serializable {
    private static final long serialversionuid = 3409768855488864675l;
    private string id;
    private string name;
    private string password;
    public user() {
    }
    public user(string id, string name, string password) {
        this.id = id;
        this.name = name;
        this.password = password;
    }
    public string getid() {
        return id;
    }
    public void setid(string id) {
        this.id = id;
    }
    public string getname() {
        return name;
    }
    public void setname(string name) {
        this.name = name;
    }
    public string getpassword() {
        return password;
    }
    public void setpassword(string password) {
        this.password = password;
    }
    public string tostring() {
        return "user [id=" + id + ", name=" + name + ", password=" + password + "]";
    }
}

abstractredisbasedao.java

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package com.redis.test;
import org.springframework.data.redis.core.redistemplate;
import org.springframework.data.redis.serializer.redisserializer;
public abstract class abstractredisbasedao<k, v=""> {
  protected redistemplate<k, v=""> redistemplate;
public redistemplate<k, v=""> getredistemplate() {
    return redistemplate;
}
public void setredistemplate(redistemplate<k, v=""> redistemplate) {
    this.redistemplate = redistemplate;
}
/**
   * 獲取 redisserializer
   */
protected redisserializer<string> getredisserializer() {
    return redistemplate.getstringserializer();
}
}

iuserdao.java

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package com.redis.test;
import java.util.list;
public interface iuserdao {
    /** 新增 */
    boolean add(user user);
    /** 批量新增,pipeline方式 */
    boolean add(list<user> list);
    /** 刪除 */
    void delete(string key);
    /** 批量刪除 */
    void delete(list<string> keys);
    /** 更新 */
    boolean update(user user);
    /** 讀取 */
    user get(string keyid);
}

userdao.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
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
package com.redis.test;
import java.util.list;
import org.springframework.dao.dataaccessexception;
import org.springframework.data.redis.connection.redisconnection;
import org.springframework.data.redis.core.rediscallback;
import org.springframework.data.redis.serializer.redisserializer;
import org.springframework.util.assert;
public class userdao extends abstractredisbasedao<string, user=""> implements iuserdao {
  public boolean add(final user user) {
    boolean result = redistemplate.execute(new rediscallback<boolean>() {
        public boolean doinredis(redisconnection connection) throws dataaccessexception {
            redisserializer<string> serializer = getredisserializer();
            byte[] key = serializer.serialize(user.getid());
            // 將id序列化成key
            byte[] value = serializer.serialize(user.getname());
            return connection.setnx(key, value);
        }
    }
    );
    return result;
}
public boolean add(final list<user> list) {
    assert.notempty(list);
    boolean result = redistemplate.execute(new rediscallback<boolean>() {
        public boolean doinredis(redisconnection connection) throws dataaccessexception {
            redisserializer<string> serializer = getredisserializer();
            for (int i = 0; i < list.size(); i++) {
                user user = list.get(i);
                byte[] key = serializer.serialize(user.getid());
                // 將id序列化成key
                byte[] value = serializer.serialize(user.getname());
                connection.setnx(key, value);
            }
            return true;
        }
    }
    , false, true);
    return result;
}
public void delete(string key) {
    redistemplate.delete(key);
}
public void delete(list<string> keys) {
    redistemplate.delete(keys);
}
public boolean update(final user user) {
    string key = user.getid();
    if(get(key) == null) {
        throw new nullpointerexception("數據行不存在,key = " + key);
    }
    boolean result = redistemplate.execute(new rediscallback<boolean>() {
        public boolean doinredis(redisconnection connection) throws dataaccessexception {
            redisserializer<string> serializer = getredisserializer();
            byte[] key = serializer.serialize(user.getid());
            // 將id序列化成key
            byte[] value = serializer.serialize(user.getname());
            connection.set(key, value);
            return true;
        }
    }
    );
    return result;
}
public user get(final string keyid) {
    user user = redistemplate.execute(new rediscallback<user>() {
        public user doinredis(redisconnection connection) throws dataaccessexception {
            redisserializer<string> serializer = getredisserializer();
            byte[] key = serializer.serialize(keyid);
            byte[] value = connection.get(key);
            if(value == null) {
                return null;
            }
            string name = serializer.deserialize(value);
            return new user(keyid, name, null);
        }
    }
    );
    return user;
}
}

redistest.java(junit測試類)

?
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
package com.redis.test;
import java.util.arraylist;
import java.util.list;
import org.junit.test;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.test.context.contextconfiguration;
import org.springframework.test.context.junit4.abstractjunit4springcontexttests;
import org.springframework.util.assert;
/**
 * junit在spring context環境下測試
 */
@contextconfiguration(locations={"classpath*:beans.xml"})
public class redistest extends abstractjunit4springcontexttests {
    @autowired
      private iuserdao userdao;
    /** 增加單個用戶 */
    @test
      public void testadduser() {
        user user = new user("user1", "password1", null);
        boolean result = userdao.add(user);
        assert.istrue(result);
        system.out.println("添加結果:" + result);
    }
    /** 批量新增普通方式,5286ms */
    @test
      public void testaddusers1() {
        list<user> list = new arraylist<user>();
        for (int i = 10; i < 50000; i++) {
            user user = new user();
            user.setid("user" + i);
            user.setname("password" + i);
            list.add(user);
        }
        long begin = system.currenttimemillis();
        for (user user : list) {
            userdao.add(user);
        }
        system.out.println(system.currenttimemillis() - begin);
    }
    /** 批量新增pipeline方式,484ms */
    @test
      public void testaddusers2() {
        list<user> list = new arraylist<user>();
        for (int i = 50000; i < 100000; i++) {
            user user = new user();
            user.setid("user" + i);
            user.setname("password" + i);
            list.add(user);
        }
        long begin = system.currenttimemillis();
        boolean result = userdao.add(list);
        assert.istrue(result);
        system.out.println(system.currenttimemillis() - begin);
    }
    /** 更新 */
    @test
      public void testupdate() {
        user user = new user();
        user.setid("user1");
        user.setname("new_password");
        boolean result = userdao.update(user);
        assert.istrue(result);
    }
    /** 刪除 */
    @test
      public void testdelete() {
        string key = "user1";
        userdao.delete(key);
    }
    /** 批量刪除 */
    @test
      public void testdeletes() {
        list<string> list = new arraylist<string>();
        for (int i = 0; i < 10; i++) {
            list.add("user" + i);
        }
        userdao.delete(list);
    }
    /** 讀取 */
    @test
      public void testgetuser() {
        string id = "user1";
        user user = userdao.get(id);
        assert.notnull(user);
        system.out.println(user);
    }
}

總結

以上就是本文關于spring集成redis詳解代碼示例的全部內容,希望對大家有所幫助。如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!

 

原文鏈接:https://www.2cto.com/kf/201609/543944.html

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 成人私人影院在线版 | 男女男在线精品网站免费观看 | 欧美一级片免费在线观看 | www.av在线视频 | 美女脱衣有肉 | 秋霞黄色片| 3d欧美人禽交| 日韩一级片在线播放 | 国产美女做爰免费视频软件 | 忘忧草在线社区WWW日本-韩国 | 国产免费资源高清小视频在线观看 | 日本人与黑人做爰视频网站 | 欧美一区欧美二区 | 男女被爆动漫羞羞动漫 | 精品国产成人高清在线 | 国产一卡二卡3卡4卡四卡在线视频 | 99久久精品免费精品国产 | 蜜桃在线 | 小早川怜子在线播放精品 | 色综合久久丁香婷婷 | 亚洲天堂男人的天堂 | 1024国产看片在线观看 | 欧美一区二区三区视视频 | 波多野结衣女老师 | 日本一区二区三区在线 观看网站 | 欧洲一级| 91动漫在线观看 | 亚洲高清毛片一区二区 | 日韩综合一区 | 国产香蕉97碰碰在线视频 | 日韩免费高清专区 | 亚洲香蕉伊在人在线观婷婷 | 好湿好紧太硬了我太爽了网站 | 每天都要睡男人(nph) | 日韩免费在线视频观看 | 国产有码在线 | aⅴ视频在线免播放观看 | 日韩 欧美 国产 亚洲 中文 | 精品久久看 | 日韩理论片在线看免费观看 | 久久精品男人影院 |