1 , 利用 printemps-data-redis 整合
项目使用的 pom.xml:
<project xmlns = "http://maven.apache.org/pom/4.0.0" xmlns: xsi = "http://www.w3.org/2001/xmlschema-instance" xsi: schemalation = "http://maven.apache.org/pom/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd "> <Modelversion> 4.0.0 </ ModelVersion> <proupId> com.x.redis </ groupeid> <ArtifActid> Spring_redis </ Artifactid> <version> 1.0-Snapshot </De version> <packaging> <url> http://maven.apache.org </url> <properties> <project.build.sourceencoming> utf-8 </project.build.sourceencoding> </properties> <peedences> <dependency> <proupId> org.springframework.data </preentend>> <proupId> org.springframework.data </prandid> <ArtefactId> Spring-data-redis </letefactId> <DERSE> 1.0.2.release </DERNIERSE> </DENDENCENCE> <Dependance> <GroupId> Org.SpringFramework </proupId> <ArtefactId> Spring-core </ artifactid> <version> 3.1.2.Release </preentency> </ Dependency> <pouprid> redis.client </preedId> <ArtefactId> Jedis </ artifactid> <DERSE> 2.1.0 </ Version> </ Dependency> <Dedency> <GroupId> JUnit </prôdId> <ArtifActid> JUnit </ Artifactid> <Dersond> 4.8.2 </-version> <cope> Test </cope> </Dedency> <Dedency> <GroupID> ORG.SLF4j </ GroupID> <ArtefactId> SLF4J-API </ Artifactid> <Dersion> 1.6.1 </DERNIERSE> </DENDENCENCY> <! - 将现有的 JAKARTA Commons Logging 的调用转换成 LSF4J 的调用。 -> <Dedency> <ProupID> ORG.SLF4J </ GroupID> <Retifactive> JCL-Over-SLF4J </letifactid> <Dudera> </Dependency> <! - Hack: : 确保 Commons-Logging 的 Jar 包不被引入 , 否则将和 JCL-OVER-SLF4J 冲突 -> <Dedency> <proupId> Commons-Logging </prôdId> <ArtefactId> Commons-Logging </pope> </Dedency> <! - SLF4J 的实现 : Logback , 用来取代 Log4j 。更快、更强! -> <dependency> <proupId> Ch.qos.logback </promdId> <ArtifActid> Logback-Classic </ ArtifactId> <Dudition> 0.9.24 </ptep> <ccope> Runtime </ Scope> </Dependance> </Dependance> </propre>
除了 Log 部分 , 只有一个 Core de ressort 和 printemps-data-redis 了
:
applicationContext.xml:
1 , Contexte: propriété-placeholder 标签用来导入 Propriétés 文件。从而替换 $ {redis.maxidle} 这样的变量。
2 , Contexte: composant-scan 是为了在 com.x.redis.dao 报下的类能够实用 printemps 的注解注入的方式。
3 , 事实上我们只需要把 Jedispoolconfig 配数来就好了 , 接下来就是 Spring 的封装了。所以直接看 Userdaoimpl 的实现就明白了。
<? xml version = "1.0" encoding = "utf-8"?> <beans xmlns = "http://www.springframework.org/schema/beans" xmlns: xsi = "http://www.w3.org/2001/xmlschema-instance" xmlns: p = "http://www.springframework.org/schema/p" xmlns: context = "http://www.springframework.org/schema/Contex xmlns: tx = "http://www.springframework.org/schema/tx" xmlns: aop = "http://www.springframework.org/schema/aop" xsi: schemalation = "http://www.spring http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd ">; Location = "ClassPath: redis.properties" /> <context: composant-scan base-package = "com.x.redis.dao"> </ context: composant-scan> <bean id = "PoolConfig"> <propriété name = "maxidle" value = " <propriété name = "maxwait" value = "$ {redis.maxwait}" /> <propriété name = "testonBorrow" value = "$ {redis.testonborrow}" /> </ bean> <bean id = "ConnectionFactory" p: host-name = "$ {redis.host}" p: port = "$ {redis.port}" "" P: Password = "$ {redis.pass}" P: Pool-Config-Ref = "PoolConfig" /> <Bean Id = "Redistetemplate"> <propriété name = "ConnectionFactory" Ref = "ConnectionFactory" /> </Ean> <Bean Id = "Userdao" /> </ Beans> redis.properties:
# Redis Paramètres # redis.host = 192.168.20.101 # redis.port = 6380 # redis.pass = fooBaredRis.host = 127.0.0.1redis.port = 6379redis.pass = redis.Maxidle = 300restonBorwer = TRUEAL = 600redis.MaxwitE
Userdaoimpl :
1 , printemps 对 Dao 层的封装很多用了类似于下面代码的模板方式。
2 , Redemplate 就是 printemps 对 redis 的一个封装而已。
classe publique UserDaOIMPL implémente UserDao {@Autowired Protected ReDistetemplate <Serializable, Serializable> Redemplate; public void SaveUser (utilisateur d'utilisateur final) {redesttemplate.execute (new redisCallback <objet> () {@Override public objet doInredis (Redisconnection Connection) lève DataCessexception {Connection.set (redemplate.getId ()),. redistEmplate.getStringSerializer (). Serialize (user.getName ()); } @Override public utilisateur GetUser (final id long) {return reidemplate.execute (new redisCallback <User> () {@Override public utilisateur doInredis (Redisconnection Connection) lève DataCcessException {byte [] key = redestemlate.getStringSerializer (). Serialize ("user.uid." + Id); = Connection.get (Key); }}:
Utilisateur:
classe publique User {private long id; nom de chaîne privé; public long getID () {return id; } public void setid (long id) {this.id = id; } public String getName () {Nom de retour; } public void setName (string name) {this.name = name; }} :
public static void main (string [] args) {applicationContext ac = new ClassPathxmlApplicationContext ("classPath: /ApplicationContext.xml"); Userdao userdao = (userdao) ac.getBean ("userdao"); User user1 = new User (); user1.setid (1); user1.setName ("Obama"); UserDao.Saveuser (User1); User user2 = userdao.getUser (1); System.out.println (user2.getName ()); }2 , 不利用 printemps-data-redis 整合
个人觉得这样整合灵活度更大 , 能够更加明了的完成任务。
pom.xml:
<project xmlns = "http://maven.apache.org/pom/4.0.0" xmlns: xsi = "http://www.w3.org/2001/xmlschema-instance" xsi: schemalation = "http://maven.apache.org/pom/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd "> <ModelVersion> 4.0.0 </ ModelVersion> <ProupId> com.d.work </proupId> <ArtifActid> redis_Templete </ Artifactid> <version> 1.0-snapshot </-version> <packaging> jar </ package> <name> redis_templete </name> <url> http://maven.apache.org </url> <properties> <project.build.sourceencoding> utf-8 </project.build.sourceencoding> </properties> <dependance> <dependency> <proupId> junit </proutid> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.1.0</version> </dependency> <dependency> <groupId>org.springframework</groupId> <ArtefactId> Spring-core </ artifactid> <DERSE> 3.1.2.Release </ Version> </Dependency> <Dedency> <GroupId> org.springFramework </proupId> <Artefactive> Spring-Beans </letefactive> <in version> 3.1.22 <ArtefactId> Spring-Context </ artifactid> <DERSE> 3.1.2.Release </ version> </Dependency> <Dedency> <ProupId> org.slf4j </proupId> <ArtefactId> Slf4j-API </ Artifactid> <version> 1.6.1 </De version> </Dedency> <! <dependency> <proupId> org.slf4j </proupId> <Ertifactid> jcl-over-slf4j </ artifactid> <version> 1.6.1 </-version> </pedidency> <! - Hack : 确保 Commons-Logging 的 Jar 包不被引入 , 否则将和 Jcl-over-slf4j 冲突 --> <dependency> <ArtefactId> Commons-Logging </ Arfactive> <Sease> 1.1.1 </DERNIFRIENT> <COPE> Fourni </cope> </ Dependency> <! - SLF4J 的实现 : Logback , 用来取代 Log4J 。更快、更强! -> <Dedency> <ProupId> ch.qos.logback </proupId> <artifactid> Logback-Classic </ ArfactId> <version> 0.9.24 </ version> <ccope> Runtime </ccope> </dependency> </dependces> </randing>
:
data-trven.xml
1 , Contexte: propriété-placeholder 和 Contexte: composant-scan 前面解释过啦。
2 , 配置了一个 Shardedjedispool , 在 Jdeis 里 还有个 Jedispool 。这两个的区别:
一个是分片形式 , 可以连接有主备的 redis 服务端 , 一个是单个的。详细后续学习
3 , 因为不使用 printemps-data-redis 的封装 , 所以自己要自己封装一个
<? xml version = "1.0" encoding = "utf-8"?> <beans xmlns = "http://www.springframework.org/schema/beans" xmlns: xsi = "http://www.w3.org/2001/xmlschema-instance" xmlns: p = "http://www.springframework.org/schema/p" xmlns: context = "http://www.springframework.org/schema/Contex xmlns: tx = "http://www.springframework.org/schema/tx" xmlns: aop = "http://www.springframework.org/schema/aop" xsi: schemalation = "http://www.spring http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd ">; Location = "CLASSPATH: redis.properties" /> <context: composant-scan Base-Package = "com.d.work.main"> </ context: ComponentScan> <context: Component-Scan Base-Package = "com.dispoolConfig"> </ Property Name = "MAXACTIVE" / "/> <<toftans" name = "maxidle" value = "8" /> <propriété name = "maxwait" value = "1000" /> <propriété name = "testonborrow" value = "true" /> <propriété name = "testonreturn" value = "true" /> <! <constructor-arg index = "0" ref = "jedispoolconfig" /> <constructor-arg index = "1"> <sthost> <ean> <constructor-arg name = "host" value = "$ {redis.host}" /> <constructor-arg name = "port" value = "$ {redis.port}" /> <constructeur-arg name = "timeout" value = "$ {redis.timeout}" /> <constructor-arg name = "ponde" value = "1" /> </ank> </sist> </ constructor-arg> </ank> </bans>Redisdatasource: 定义三个方法
interface publique redisdatasource {public abstrait shardedjedis getRedisclient (); public void returnResource (Shardedjedis Shardedjedis); public void returnResource (Shardedjedis Shardedjedis, booléen brisé);}实现 redisdatasource:
1, 注入配置好的 Shardedjedispool , 这三个方法的作用 :
@Repository ("redisdatasource") classe publique RedisDataSourceImpl implémente redisdataSource {private static final logger log = loggerfactory.getLogger (redisdatasourceImpl.class); @Autowired Private Shardedjedispool Shardedjedispool; public shardedjedis getRedisclient () {try {shardedjedis shardjedis = shardedjedispool.getResource (); retour Shardjedis; } catch (exception e) {Log.Error ("GetRediscent Error", E); } return null; } public void returnResource (Shardedjedis Shardedjedis) {Shardedjedispool.returnResource (Shardedjedis); } public void returnResource (Shardedjedis shardedjedis, booléen brisé) {if (brisé) {shardedjedispool.returnbrokedResource (Shardedjedis); } else {shardedjedispool.returnResource (Shardedjedis); }}}第二层的封装 : RedislientTemplate , 例子实现了放值和取值。最后代码提供了全部命令的实现。
代码就是映射性质的又一次调用 Jedis 的方法而已 , 用了个 cassé 来做标示符 , 决定返还资源的方式。
这一层的目的主要也是让再上层的调用不需要关心 Pool 中链接的取得和返还问题了。
@Repository ("RedislientTemplate") Classe publique RedientTemplate {private static final logger log = loggerfactory.getLogger (rediscientTemplate.class); @Autowired private redisdatasource redisdatasource; public void disconnect () {shardedjedis shardedjedis = redisdatasource.getRedisclient (); Shardedjedis.Disconnect (); } / ** * 设置单个值 * * @param key * @param value * @return * / public String set (string key, string value) {String result = null; Shardedjedis Shardedjedis = redisdatasource.getRedisclient (); if (shardedjedis == null) {return result; } booléen brisé = false; try {result = shardedjedis.set (key, valeur); } catch (exception e) {log.error (e.getMessage (), e); Broken = true; } Enfin {redisdatasource.returnResource (Shardedjedis, cassé); } Retour Résultat; } / ** * 获取单个值 * * @param key * @return * / public String get (string key) {String result = null; Shardedjedis Shardedjedis = redisdatasource.getRedisclient (); if (shardedjedis == null) {return result; } booléen brisé = false; try {result = shardedjedis.get (key); } catch (exception e) {log.error (e.getMessage (), e); Broken = true; } Enfin {redisdatasource.returnResource (Shardedjedis, cassé); } Retour Résultat; }}:
public static void main (string [] args) {applicationContext ac = new ClassPathxmlApplicationContext ("classpath: /data-source.xml"); RedislientTemplate Redislient = (re-divientTemplate) ac.getBean ("re-divientTemplate"); redislient.set ("a", "ABC"); System.out.println (Redislient.get ("A")); }附上 RedislientTemplate ::
RedislientTemplate 代码太多 , 附上下载地址 : http: //xiazai.vevb.com/201701/yuanma/redisclientTemplate_jb51.rar
以上就是本文的全部内容 , 希望对大家的学习有所帮助 , 也希望大家多多支持武林网。