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.romp.romp.romp. 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> <rerl> http://maven.apache.org </rerl> <properties> <poject.build.sourceencoding> UTF-8 </project.build.sourceencoding> </Properties> <dependencies> <groupid> <groupid> org.springframework. <ArTifactId> Spring-Data-Redis </arttifactid> <version> 1.0.2.release </version> </dependency> <dependency> <groupid> org.springframework </sroupid> <ArtiFacTID> SPRING-CORE </arttifactid> <version> 3.1.2.release </Version> </Dependency> </Dependency> </Versies. <ArtifactId> jedis </stifactid> <version> 2.1.0 </version> </dependency> <dependency> <groupid> Junit </sroupid> <ArTifactId> Junit </artifactid> <version> 4.8.2 </Versi> <cope> Test </scope> </Dependency> <version> </Version> <scope> </scope> </dependency> <version> </Version> </scope. <ArtifactId> slf4j-api </arttifactid> <version> 1.6.1 </version> </dependency> <!-将现有的 Jakarta Commons Logging 的调用转换成 lsf4j 的调用。-> </org.sif4j </groupid> <Artifactid> JCl-over-over-org. </Dependency> <!-Hack : 确保 Commons-logging 的 JAR 包不被引入 , 否则将和 JCl-over-Slf4j 冲突-> <dependency> <Groupid> Commons-logging </groupid> <Artifactid> Commons-logging </Stifactid> <2 versi> 1.1.1 </Versi> </COMPOPED> </artifactid> </Versi </Versi> </Versi </Versi> </Versi </Versi> </Versi> SLF4J 的实现 : Logback , 用来取代 Log4j 。更快、更强!-> <dependency> <GroupId> ch.qos.logback </groupid> <ArTifactId> Logback-Classic </Artifactid> <Version> 0.9.24 </Versi> <scope> Runtime </scope> </Dependency> </Dependencies> </Project
除了 log 部分 , 只有一个 Spring Core 和 Spring-Data-Redis 了
项目文件目录结构 :
ApplicationContext.xml :
1 , Konteks: Properti-PlaceHolder 标签用来导入 Properti 文件。从而替换 $ {redis.maxidle} 这样的变量。
2, konteks: komponen-scan 是为了在 com.x.redis.dao 报下的类能够实用 Spring 的注解注入的方式。
3 , 事实上我们只需要把 JedispoolConfig 配数来就好了 , 接下来就是 Spring 的封装了。所以直接看 UserdaoImpl 的实现就明白了。
<? XML Versi = "1.0" encoding = "utf-8"?> <beans xmlns = "http://www.springframework.org/schema/beans" xmlns: xsi = "http://www.w3.org/2001/xmls xmlns: p = "http://www.springframework.org/schema/p" xmlns: context = "http://www.springframework.org/schema/context" xmlns: jee = "http:/schema/clns: jee =" http:/schaMe/seMe/jee " xmlns: tx = "http://www.springframework.org/schema/tx" xmlns: aop = "http://www.springframework.org/schema/aop" xsi: schemalocation = "http:/schema/aop" xsi: schemalocation = "http:/schema.aop" http://www.springframework.org/schema/beans/spring-teans.xsd http://www.spramework.org/schema/context http:/www.springframework.org/schema/context location="classpath:redis.properties" /> <context:component-scan base-package="com.x.redis.dao"> </context:component-scan> <bean id="poolConfig"> <property name="maxIdle" value="${redis.maxIdle}" /> <property name="maxActive" value="${redis.maxActive}" /> <property name="maxWait" value="${redis.maxWait}" /> <property name="testOnBorrow" value="${redis.testOnBorrow}" /> </bean> <bean id="connectionFactory" p:host-name="${redis.host}" p:port="${redis.port}" P: kata sandi = "$ {redis.pass}" p: pool-config-ref = "poolconfig"/> <bean id = "redistemplate"> <name properti = "connectionFactory" ref = "connectionFactory"/> </bean> <bean id = "userdao"/</bean> redis.properties :
#Pengaturan Redis#redis.host = 192.168.20.101#redis.port = 6380#redis.pass = foobaredredis.host = 127.0.0.1redis.port = 6379redis.pass = redis.maxidle = 300redis.Maxactive = 600Redis = pialax = Maxidle = 300redis.Maxactive = 600Redis.max.max = 300Redis
UserdaoImpl :
1, musim semi 对 dao 层的封装很多用了类似于下面代码的模板方式。
2, redistemplate 就是 pegas 对 redis 的一个封装而已。
Public Class UserdaoImpl mengimplementasikan userdao {@Autowired dilindungi redistemplate <serializable, serializable> redistemplate; public void saveUser (pengguna pengguna akhir) {redistemplate.execute (Rediscallback baru <POMPERTIF> () {@Override Objek publik DoInredis (Redisconnection Connection) melempar DataAccessException {Connection.set (Redistemple.getstringserizer (). Serialize ("user.uid." + redistemplate.getstringserializer (). Serialize (user.getName ())); } @Override pengguna publik getUser (ID panjang akhir) {return redistemplate.execute (rediscallback baru <User> () {@Override pengguna publik doinredis (redisconnection connection) melempar dataAccessException {byte [] = redistemplate.getStringSerizer (). byte [] connection.get (Key); }}其他 :
Pengguna:
pengguna kelas publik {private long ID; nama string pribadi; publik long getId () {return id; } public void setId (Long ID) {this.id = id; } public string getName () {return name; } public void setName (name string) {this.name = name; }}测试代码 :
public static void main (string [] args) {applicationContext ac = new classpathxMlappleCicedContext ("classpath: /AppLicationContext.xml"); Userdao userdao = (userdao) ac.getBean ("userdao"); Pengguna pengguna1 = pengguna baru (); 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.romp.romp.romp. http://maven.apache.org/xsd/maven-4.0.0.xsd "> <podelversion> 4.0.0 </podelversion> <groupid> com.d.work </groupid> <ArTifactid> Redis_templete </ArtifactId> </Groupid> <ArTifacTID> Redis_TempleTE </ArtifactId> <versi> 1.0-snapshot </packaging </artifacping </artifacping> </versi 1.0-snapshot </packaging </artifacping> </version> 1.0-snapshot </packaging </artifacaging </artifacping> </version> 1.0-snapshot </snapsaging </artifacaging </artifacaging </artifacaging </version> 1.0-snapshapes <name> redis_templeTe </name> <rerl> http://maven.apache.org </ruRl> <properties> <poject.build.sourceencoding> UTF-8 </project.build.sourceencoding> </Properties> <dependensies> </project.build.sourceencoding> </Properties> <gandendency> </groupper> <pupup> <proupper> <puppuper> </properties> </properties> </properties> </properties> </properties> </properties> </properties> </properties> </properties> <proupt> </properties> <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> <version> 3.1.2.release </version> </gandendency> <dependency> <GroupId> org.springframework </groupid> <ArtifactId> Spring-beans </arttifactid> <version> 3.1.2.release </version> </dependency> <groupid> <groupid> org.springframework </versif> </depgerid> <groupid> <groupid> org.springframework </Version> </depgerid> <groupt> <groupsex <version> 3.1.2.release </version> </dependency> <dependency> <groupid> org.slf4j </proupid> <ArtifactId> Slf4j-API </artifactid> <version> 1.6.1 </version> </gandrency> <!-将现有的 Jakarta LOGGING 的调用转换成 LSF4J4 LSF4J4 <groupId> org.slf4j </sroupid> <ArtifactId> jcl-over-slf4j </artifactid> <version> 1.6.1 </version> </gantage> <!-Hack : 确保 commons 的 commons> <group> , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , over over over over comons logging 的<ArtifactId> Commons-logging </artifactid> <version> 1.1.1 </version> <scope> disediakan </opope> </dependency> <!-slf4j 的实现 : logback , , log4j 。更快、更强! </09.2. <scope> runtime </ scope> </dependency> </dependencies> </project>
目录结构 :
data-source.xml
1, konteks: pemegang tempat properti 和 konteks: komponen-scan 前面解释过啦。
2, 配置了一个 Shardedjedispool , 在 Jdeis 里 还有个 Jedispool 。这两个的区别:
一个是分片形式 , 可以连接有主备的 redis 服务端 , 一个是单个的。详细后续学习
3 , 因为不使用 Spring-Data-Redis 的封装 , 所以自己要自己封装一个
<? XML Versi = "1.0" encoding = "utf-8"?> <beans xmlns = "http://www.springframework.org/schema/beans" xmlns: xsi = "http://www.w3.org/2001/xmls xmlns: p = "http://www.springframework.org/schema/p" xmlns: context = "http://www.springframework.org/schema/context" xmlns: jee = "http:/schema/clns: jee =" http:/schaMe/seMe/jee " xmlns: tx = "http://www.springframework.org/schema/tx" xmlns: aop = "http://www.springframework.org/schema/aop" xsi: schemalocation = "http:/schema/aop" xsi: schemalocation = "http:/schema.aop" http://www.springframework.org/schema/beans/spring-teans.xsd http://www.spramework.org/schema/context http:/www.springframework.org/schema/context Lokasi = "ClassPath: Redis.Properties" /> <konteks: komponen-scan-package = "com.d.work.main"> < /context: component-scan> <konteks: komponen-scan base-package = "com.d.work.redis"> < /konteks: component-scan> <bean id = "jedispoolfig" <"component name =" "" "jedispool componic =" "jedispool" < /componic: "JEDISPOOL" MAXACIF = "" JEDISPOOL "MAXACIF =" COMPONENT; name = "maxidle" value = "8"/> <name properti = "maxwait" value = "1000"/> <name properti = "testonborring" value = "true"/> <properti name = "testonreturn" value = "true"/> <!-<properti nama = "testwhileIdle" value = "true"/—> </bean> "ID =" ID = "BEANDEP =" true "/—> </bean>" ID = "ID =" ID = "ID =" ID = "ID =" ID = "ID =" ID = "ID =" ID = "ID =" ID = "ID =" ID = "BEAN> </ID =" ID = "ID =" ID/BEAN/BEAN/BEAN/BEANDLEDLE = <constructor-arg index = "0" ref = "jedispoolconfig" /> <constructor-arg index = "1"> <cist> <bean> <konstruktor-arg name = "host" value = "$ {redis.host}" /> <konstruktor-arg nama = "port" value = "$ {redis.port}" /<konstruktor-arg = "port" value = "$ {redis.por}" / value = "$ {redis.timeout}"/> <constructor-arg name = "weight" value = "1"/> </t bean> </list> </constructor-Arg> </bean> </bean>RedisDataSource: 定义三个方法
antarmuka publik redisdataSource {public abstrak shardedjedis getredisclient (); public void returnResource (shardedjedis shardedjedis); public void returnResource (shardedjedis shardedjedis, boolean rusak);}实现 RedisdataSource:
1, 注入配置好的 Shardedjedispool , : :
@Repository ("RedisDataSource") Kelas Publik RedisDataSourceImpl mengimplementasikan RedisDataSource {private static final Logger log = loggerFactory.getLogger (redisDataSourceImpl.class); @Autowired pribadi shardedjedispool shardedjedispool; public shardedjedis getredisclient () {coba {shardedjedis shardjedis = shardedjedispool.getResource (); kembali Shardjedis; } catch (exception e) {log.error ("getRedisclent error", e); } return null; } public void returnResource (shardedjedis shardedjedis) {shardedjedispool.returnresource (shardedjedis); } public void returnResource (shardedjedis shardedjedis, boolean rusak) {if (rusak) {shardedjedispool.returnbrokenResource (shardedjedis); } else {shardedjedispool.returnResource (shardedjedis); }}}第二层的封装 : RedisClientTemplate , ,
代码就是映射性质的又一次调用 jedis 的方法而已 , 用了个 rusak 来做标示符 , 决定返还资源的方式。
这一层的目的主要也是让再上层的调用不需要关心 Pool 中链接的取得和返还问题了。
@Repository ("RedisClientTemplate") kelas publik RedisClientTemplate {private static final Logger log = loggerFactory.getLogger (redisClientTemplate.class); @Autowired Private RedisDataSource RedisDataSource; public void disconnect () {shardedjedis shardedjedis = redisdataSource.getredisclient (); shardedjedis.disconnect (); } / ** * 设置单个值 * * @param Key * @param value * @return * / public string set (tombol string, nilai string) {string result = null; Shardedjedis shardedjedis = redisdataSource.getredisclient (); if (shardedjedis == null) {hasil pengembalian; } boolean rusak = false; coba {hasil = shardedjedis.set (key, value); } catch (exception e) {log.error (e.getMessage (), e); rusak = true; } akhirnya {redisDataSource.ReturnResource (shardedjedis, rusak); } hasil pengembalian; } / ** * 获取单个值 * * @param Key * @return * / public string get (tombol string) {string result = null; Shardedjedis shardedjedis = redisdataSource.getredisclient (); if (shardedjedis == null) {hasil pengembalian; } boolean rusak = false; coba {hasil = shardedjedis.get (key); } catch (exception e) {log.error (e.getMessage (), e); rusak = true; } akhirnya {redisDataSource.ReturnResource (shardedjedis, rusak); } hasil pengembalian; }}测试代码 :
public static void main (string [] args) {applicationContext ac = new classpathxmlapplicationContext ("classpath: /data-source.xml"); RedisClientTemplate redisclient = (redisclienttemplate) ac.getBean ("redisclienttemplate"); redisclient.set ("A", "ABC"); System.out.println (redisclient.get ("a")); }附上 redisclienttemplate 全部实现 :
RedisClientTemplate 代码太多 , 附上下载地址 : http: //xiazai.vevb.com/201701/yuanma/redisclienttemplate_jb51.rar
以上就是本文的全部内容 , 希望对大家的学习有所帮助 , 也希望大家多多支持武林网。