1 , 利用 Spring-Data-Redis 整合
项目使用的 pom.xml :
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.x.redis</groupId> <artifactId>Spring_redis</artifactId> <version>1.0-SNAPSHOT</version> <packaging>jar</packaging> <name>Spring_redis</name> <URL> http://maven.apache.org </url> <properties> <project.build.sourceEncoding> utf-8 </project.build.sourceencoding> </свойства> <Depertiencies> <dehyed> <groupid> org.sprame.data </Groupid> <ArtifactId> Spring-Data-Redis </artifactId> <sersive> 1.0.2.release </version> </dependency> <Depective> <groupid> org.springframework </GroupId> <ratifactId> Spring-Core </artifactid> <serse> 3.1.2.release </version> </rederency> <GroupId> <persion> red. <ratifactid> jedis </artifactid> <sersion> 2.1.0 </version> </dependency> <dependency> <groupid> junit </GroupId> <strifactid> junit </artifactid> <sersion> 4.8.2 </version> <compope> test </scope> </repertice> <Deving> <groupd> org.slf4 <ArtifactId> slf4j-api </artifactid> <sersive> 1.6.1 </version> </dependency> <!-将现有的 jakarta commons logging 的调用转换成 lsf4j 的调用。-> <dehydency> <groupid> org.slf4j </groupd> <artifactid> jcl-over-slf4j </artifactid> </artifactid> jcl-over-slf4j </artifactid> </artifactid> jcl-over-slf4j </artifactid> </artifactid> artifactid> argefactid> <perifactid> jcl-over-slf4j </artifactid> <!-Hack : 确保 Commons-Logging 的 jar 包不被引入 , 否则将和 jcl-over-slf4j 冲突-> <dependency> <groupid> commons-logging </groupid> <artifactid> commons-logging </artifactid> <serview> 1.1.1 </версия> <cerpope> предоставлена </scope> </зависимость> <! SLF4J 的实现 : LOGACK , 用来取代 LOG4J 。更快、更强!-> <Dependency> <groupId> ch.qos.logback </GroupId> <strifactid> rogack-classic </artifactid> <seriation> 0.9.24 </version> <cracpope> runtime </scope> </depertion> </depertive> </project>
除了 log 部分 , 只有一个 Spring Core 和 Spring-Data-Redis 了 了
项目文件目录结构 :
ApplicationContext.xml :
1 , Контекст: Property Placeholder 标签用来导入 Свойства 文件。从而替换 $ {redis.maxidle} 这样的变量。
2 , Контекст: компонент-сканирование 是为了在 com.x.redis.dao 报下的类能够实用 пружина 的注解注入的方式。
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/context" xmlns: jee = "http://www.springframe.orgema.orschema" http://wwww.springformawork.orgema. xmlns: tx = "http://www.springframework.org/schema/tx" xmlns: aop = "http://www.springframework.org/schema/aop" xsi: schemalocation = "http://wwww.springform. 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: component-scan base-package = "com.x.redis.dao"> < /context: component-scan> <bean id = "boolconfig"> <собственность = "maxidle" value = "$ {redis.maxidle}" /> <name = "maxictive" value = "$ {redis.maxidle}" /> <свойство = "maxactive" <name = "maxwait" value = "$ {redis.maxwait}" /> <name = "testonbourrow" value = "$ {redis.testonborw}" /> < /bean> <bean id = "connectionFactory" P: host-amame = "$ {redis.host}" p: port = "$ {redis.port.port. P: Password = "$ {redis.pass}" P: pool-config-ref = "boolconfig"/> <bean id = "redistemplate"> <name = "connectionFactory" ref = "connectionFactory"/> </bean> <bean id = "userDao"/> </> Redis.properties :
#Redis settings#redis.host = 192.168.20.101#redis.port = 6380#redis.pass = foobaredredis.host = 127.0.0.1redis.port = 6379redis.pass = redis.maxidle = 300redis.maxactacation = 600redis.maxwait = 1000red.
Userdaoimpl :
1 , Spring 对 Dao 层的封装很多用了类似于下面代码的模板方式。
2 , Redistemplate 就是 Spring 对 Redis 的一个封装而已。
открытый класс userDaoImpl реализует userdao {@autowired protected redistemplate <serializable, serializable> redistemplate; public void SaidUser (окончательный пользователь пользователя) {redistemplate.execute (new resiscallback <object> () {@Override public Object doInredis (подключение RedIsconnection) THRES DataCcessException {connection.set (redistemplate.getStringserializer (). Serialize ("user.uid. redistemplate.getStringserializer (). Serialize (user.getName ()); } @Override public user getUser (final Long Id) {return redistemplate.execute (new Rediscallback <user> () {@override public user doinredis (redisconnection connection) throws DataCcessException {byte [] key = redistemplate.getStringseriazer (). Key -exists () () () exists () exists () exists (). Value = Connection.Get (Key); }}其他 :
Пользователь:
Пользователь открытого класса {Private Long ID; Приватное название строки; public long getId () {return id; } public void setId (long id) {this.id = id; } public String getName () {return name; } public void setName (string name) {this.name = name; }}测试代码 :
public static void main (string [] args) {applicateContext ac = new classpathxmlapplicationContext ("classPath: /applicationContext.xml"); Userdao userdao = (userdao) ac.getbean ("userdao"); Пользователь пользователь1 = новый пользователь (); user1.setid (1); user1.setname ("Obama"); userdao.saveuser (user1); User user2 = userdao.getuser (1); System.out.println (user2.getName ()); }2 , 不利用 Spring-Data-Redis 整合
个人觉得这样整合灵活度更大 , 能够更加明了的完成任务。
pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.d.work</groupId> <artifactId>Redis_Templete</artifactId> <version>1.0-SNAPSHOT</version> <packaging>jar</packaging> <mame> redis_templete </name> <properties> <properties> <properties> <prop./build.sourceencoding> utf-8 <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> <artifactId>spring-core</artifactId> <sersion> 3.1.2.release </version> </depervice> <dependency> <groupid> org.springframework </groupid> <stracactid> пружина </artifactid> <sersion> 3.1.2.release </version> </artifactid> <dehyde> <groupid> org.spramework </ressure> </artifactid> <gestificte> <groupid> org.spramework </artifactid> <despectiftectid> <groupid> org.spramework </artifactid> <despectifice> <groupid> org.sprameWor <sersion> 3.1.2.reelease </version> </dependency> <dependency> <groupid> org.slf4j </groupid> <artifactid> slf4j-api </artifactid> <sersive> 1.6.1 </version> </depertive> <!-将现有的 jakarta commons logging 的调用转换成 lsf4j 的调用。 的调用。 的调用。 的调用。 的调用。 的调用。 的调用。 的调用。 的调用。 的调用。. <groupId> org.slf4j </GroupId> <ArtifactId> jcl-over-slf4j </artifactId> <sersive> 1.6.1 </version> </jope-slf4j-hack : : 确保 确保 确保 的 的 包不被引入 包不被引入 , 否则将和 jcl-over-slf4j 冲突-> <зависимость> <groupid> commons-lging-lging-lging> <artifactId>commons-logging</artifactId> <version>1.1.1</version> <scope>provided</scope> </dependency> <!-- slf4j的实现:logback,用来取代log4j。更快、更强! --> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>0.9.24</version> <Scope> время выполнения </scope> </depertion> </depertionlies> </project>
目录结构 :
data-source.xml
1 , Контекст: Property Placeholder 和 Контекст: компонент-сканирование 前面解释过啦。
2 , 配置了一个 ShardedJedispool , 在 jdeis 里 还有个 jedispool 。这两个的区别:
一个是分片形式 , 可以连接有主备的 redis 服务端 , 一个是单个的。详细后续学习
3 , 因为不使用 Spring-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/context" xmlns: jee = "http://www.springframe.orgema.orschema" http://wwww.springformawork.orgema. xmlns: tx = "http://www.springframework.org/schema/tx" xmlns: aop = "http://www.springframework.org/schema/aop" xsi: schemalocation = "http://wwww.springform. 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" /> <контекст: компонент-сканирование Base-package = "com.d.work.main"> < /context: Component-Scan> <Контекст: компонентный сканирование Base-package = "com.d.work.redis"> < /context: component-scan> <bean id = "jedispoolconfig"> <property name = "maxactive" value = " /" /"50" /" /" 50 " /" 50 " /" 50 ". name = "maxidle" value = "8"/> <property name = "maxwait" value = "1000"/> <name = "testonBorrow" value = "true"/> <name = "testonReturn" value = "true"/> <!-<name = "testwhileIdle" value = "true"/> </bean> <bean yde vecude-value value "/>-> </bean> <bean yde vecude-valued value"/>-> </bean> <! <constructor-arg index = "0" ref = "jedispoolconfig" /> <constructor-arg index = "1"> <list> <bean> <constructor-arg name = "host" value = "$ {redis.host}" /> <constructor- name = "value =" $ {redis.port} " /> <constructor-arg =" value = "$ {Redis.port}" /> <Constructor-arg = "value =" $ {Redis.port} " /> <Constructor-arg name =" $ " value = "$ {redis.timeout}"/> <constructor-arg name = "wews" value = "1"/> </bean> </list> </constructor-arg> </bean> </beans>Redisdatasource: 定义三个方法
Общественный интерфейс RedisDatasource {public Abstract shardedjedis getredisclient (); public void returnresource (shardedjedis shardedjedis); public void returnresource (shardedjedis shardedjedis, boolean broken);}实现 Redisdatasource:
1, 注入配置好的 shardedjedispool , : :
@Repository ("RedIsDataSource") открытый класс RedIsDatasourceImpl реализует RedIsDatasource {private Static Final Logger log = loggerFactory.getLogger (redisDataSourceImpl.class); @Autowired Частный shardedjedispool shardedjedispool; public shardedjedis getredisclient () {try {shardedjedis shardjedis = shardedjedispool.getresource (); возвращать shardjedis; } catch (Exception e) {log.error ("getRedisclent error", e); } return null; } public void returnResource (shardedjedis shardedjedis) {shardedjedispool.returnresource (shardedjedis); } public void returnResource (shardedjedis shardedjedis, логический сломан) {if (broken) {shardedjedispool.returnbrokenresource (shardedjedis); } else {shardedjedispool.returnresource (shardedjedis); }}}: : RedisclientTemplate , 例子实现了放值和取值。最后代码提供了全部命令的实现。
代码就是映射性质的又一次调用 jedis 的方法而已 用了个 сломан 来做标示符 , 决定返还资源的方式。 决定返还资源的方式。 决定返还资源的方式。 决定返还资源的方式。 决定返还资源的方式。 决定返还资源的方式。 决定返还资源的方式。
这一层的目的主要也是让再上层的调用不需要关心 Пул 中链接的取得和返还问题了。
@Repository ("redisclienttemplate") открытый класс resisclienttemplate {private static final log = loggerfactory.getlogger (redisclienttemplate.class); @Autowired частный Redisdatasource Redisdatasource; public void densenct () {shardedjedis shardedjedis = redisdatasource.getredisclient (); shardedjedis.disconnect (); } / ** * 设置单个值 * * @param клавиша * @param value * @return * / public String set (string wall) {string result = null; Shardedjedis shardedjedis = redisdatasource.getredisclient (); if (shardedjedis == null) {return result; } boolean broken = false; try {result = shardedjedis.set (key, value); } catch (Exception e) {log.error (e.getMessage (), e); сломанный = правда; } наконец {redisdatasource.returnresource (shardedjedis, broken); } return Result; } / ** * 获取单个值 * * @param key * @return * / public String get (string key) {string result = null; Shardedjedis shardedjedis = redisdatasource.getredisclient (); if (shardedjedis == null) {return result; } boolean broken = false; try {result = shardedjedis.get (key); } catch (Exception e) {log.error (e.getMessage (), e); сломанный = правда; } наконец {redisdatasource.returnresource (shardedjedis, broken); } return Result; }}测试代码 :
public static void main (String [] args) {ApplicationContext ac = new classpathxmlapplicationContext ("classPath: /data-source.xml"); Resisclienttemplate resisclient = (resisclienttemplate) ac.getbean ("resisclienttemplate"); redisclient.set ("a", "abc"); System.out.println (redisclient.get ("a")); }附上 resisclientTemplate 全部实现 :
RESISCLIENTTEMPLATE 代码太多 附上下载地址 : http: //xiazai.vevb.com/201701/yuanma/redisclienttemplate_jb51.rar
以上就是本文的全部内容 , 希望对大家的学习有所帮助 也希望大家多多支持武林网。