1 利用 利用 利用 利用 整合 整合 整合 整合 整合
项目使用的 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.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0. http://maven.apache.org/xsd/maven-4.0.0.xsd "> <modelVersion> 4.0.0 </modelversion> <MoupRid> com.x.redis </groupid> <artifactid> spring_redis </artifactid> <Persion> 1.0-snapshot </versever> <AtatageAging> jar </paquete </paquete </paquete </name- name </artifactiS> <PROPESSONS> <Url> http://maven.apache.org </sl> <properties> <ject.Build.SourceEncoding> UTF-8 </project.build.sourceEncoding> </propiedades> <fependencies> <epardency> <grupid> Org.springframeWork.data </groupid> <artifactid> Spring-dataisedismedis </artes <versión> 1.0.2.release </verververs> </pendency> <pendency> <MoupRoid> org.springframework </proupid> <artifactid> spring-core </arfactid> <versers> 3.1.2.release </verversion> </dependency> <epardency> <proupid> redis.clients </grupoD> <Atifactid> jedis </art. <Versión> 2.1.0 </Versión> </pendency> <Spendency> <MoupRoid> Junit </proupid> <artifactid> Junit </arifactid> <verserse> 4.8.2 </verversion> <cope> test </cope> </pendency> <pendency> <uproupid> org.slf4j </groupid> <artifactid> slf4j-api </artem <Versión> 1.6.1 </versión> </pendency> <!-将现有的 Jokarta Commons registrando 的调用转换成 lsf4j 的调用。-> <pendency> <proupid> org.slf4j </groupid> <artifactid> jcl-over-slf4j </artifactid> <versers> 1.6.1 </versión> </pendency> <!- Hack: 确保 确保 jar 的 jar 包不被引入 否则将和 否则将和 否则将和 否则将和 jcl-over-slf4j 冲突-> <pendency> <proupid> commons-logging </proupid> <artifactid> commons-logging </artifactid> <versión> 1.1.1 </version> <cope> proporcionó </cope> </pendency> <!-slf4j 的实现 : : : : : : 的实现 的实现 。更快、更强! 。更快、更强! 的实现 的实现 的实现 。更快、更强! 。更快、更强! 的实现 。更快、更强! 的实现 。更快、更强! 的实现 。更快、更强! 。更快、更强! 。更快、更强! 。更快、更强! 。更快、更强! 。更快、更强! 。更快、更强! 。更快、更强! 。更快、更强! 。更快、更强! 。更快、更强! 。更快、更强! 。更快、更强! 。更快、更强! 。更快、更强! 。更快、更强!- <Spendency> <ProupId> ch.qos.logback </proupid> <artifactid> logback-classic </arfactid> <versión> 0.9.24 </versión> <cope> runtime </cope> </dependency> </pendencs> </proyecto>
除了 log 部分 , 只有一个 Spring Core 和 Spring-Data-Redis 了
项目文件目录结构 :
ApplicationContext.xml:
1 , contexto: propiedad-placeholder 标签用来导入 propiedades 文件。从而替换 $ {redis.maxidle} 这样的变量。
2 , contexto: componente-escan 是为了在 com.x.redis.dao 报下的类能够实用 spring 的注解注入的方式。
3 事实上我们只需要把 事实上我们只需要把 jedispoolconfig 配数来就好了 , 接下来就是 spring 的封装了。所以直接看 userdaoImpl 的实现就明白了。
<? xml versión = "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.springframework.org/schema/Jee" xmlns: tx = "http://www.springframework.org/schema/tx" xmlns: aop = "http://www.springframework.org/schema/aop" xsi: schemalocation http://www.springframework.org/schema/Beans/spring-Beanss.xsd http://www.springframework.org/schema/context http://www.springFramework.org/schema/context/spring-conte-contexsd "> ubicación = "classpath: redis.properties" /> <context: component-scan base-pakage = "com.x.redis.dao"> < /context: component-scan> <bean id = "grupoConfig"> <propiedad name = "maxidle" valor = "$ {redis.maxidle}" /> <name de propiedad = "maxactive" value "$ {REDIS {.Maxactive}". /> <propiedad name = "maxwait" value = "$ {redis.maxwait}" /> <propiedad name = "testonborrow" value = "$ {redis.testonborrow}" /> < /bean> <bean id = "conexiónFactory" p: host-name = "$ {redis.host}" P: port = "$ {redis.port}" "" " p: contraseña = "$ {redis.pass}" P: prow-config-ref = "PoolConfig"/> <Bean ID = "redistemplate"> <Property Name = "Connectatory" ref = "ConnectionFactory"/> </bean> <bean id = "userdao"/> </rena> Redis.Properties:
#Configuración de redis#redis.host = 192.168.20.101#redis.port = 6380#redis.pass4
UserdaoImpl:
1 , Spring 对 Dao 层的封装很多用了类似于下面代码的模板方式。
2 , Redistemplate 就是 Spring 对 Redis 的一个封装而已。
UserDaoMpl de clase pública implementa userdao {@autewired redistemplate <Serializable, serializable> redistemplate; public void saveUser(final User user) { redisTemplate.execute(new RedisCallback<Object>() { @Override public Object doInRedis(RedisConnection connection) throws DataAccessException { connection.set(redisTemplate.getStringSerializer().serialize("user.uid." + user.getId()), redistemplate.getStringserializer (). Serialize (user.getName ())); } @Override Public User getUser (ID de largo long) {return redistEmplate.exCute (new Rediscallback <Serem> () {@Override Public User doinredis (redisConnection Connection) tira dataAccessException {byte [] key = redistEmate.getStingSerializer (). Serialize ("user.uid" + id); if); if); if); if); BYTE [] Valor = Connection.get (Key); }}其他 :
Usuario:
Usuario de clase pública {ID de largo privado; nombre de cadena privada; public Long getId () {return id; } public void setid (ID long) {this.id = id; } public String getName () {nombre de retorno; } public void setName (nombre de cadena) {this.name = name; }}测试代码 :
public static void main (String [] args) {applicationContext ac = new ClassPathXMLApPlicationContext ("classpath: /ApplicationContext.xml"); Userdao userDao = (userDao) ac.getBean ("userDao"); Usuario user1 = new User (); user1.SetId (1); user1.setName ("Obama"); userdao.saveUser (user1); Usuario user2 = userdao.getuser (1); System.out.println (user2.getName ()); }2 , 不利用 不利用 不利用 整合 整合 整合 整合 整合
个人觉得这样整合灵活度更大 能够更加明了的完成任务。 能够更加明了的完成任务。
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.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0. http://maven.apache.org/xsd/maven-4.0.0.xsd "> <modelVersion> 4.0.0 </modelversion> <MoupRoid> com.d.work </groupid> <artifactid> redis_templete </artifactid> <Persion> 1.0-snapshot </lipsion> <packaging> <name> Redis_templete </name> <sl> http://maven.apache.org </sl> <properties> <jecter.build.sourceEncoding> utf-8 </project.build.sourceEncoding> </propiedadies> <dependency> <depentency> <grupiD> junit </groupid> <artid> <Artid> <Artid> <Persion> 3.8.1 </versión> <cope> test </cope> </pendency> <pendency> <proupID> redis.clients </proupid> <artifactid> jedis </arfactid> <version> 2.1.0 </versión> </dependencia> <fependency> <uproupid> org.springFramework </groupid> <artifactid> spring -core </artiD> <versión> 3.1.2.release </verververs> </pepertency> <pendency> <grupid> org.springframework </groupid> <artifactid> spring-beans </artifactid> <version> 3.1.2.release </ververy> </dependency> <epardency> <grupid> org.springFramework </proupid> <artifactid> springctExtExt </artextex <Versión> 3.1.2.Release </versión> </pendency> <pendency> <grupoD> org.slf4j </groupid> <artifactid> slf4j-api </artifactid> <versión> 1.6.1 </versión> </pendency> <!-将现有的 jakarta commons Logging 的调用转换成 lsf4j 的调用。-> <pendency> <MoupRid> org.slf4j </groupid> <artifactid> jcl-over-slf4j </artifactid> <versión> 1.6.1 </versión> </pendency> <!-Hack : 确保 Commons Logging 的 jar 包不被引入 , , 否则将和 jCl-over-slf4j 冲突-> <Enderency> <MoupRid> commons-logging </groupid> <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> <cope> runtime </cope> </pepertency> </pendencs> </jection>
目录结构 :
data-source.xml
1 , contexto: propiedad-lugar-contexto: componente-scan 前面解释过啦。
2 , 配置了一个 配置了一个 shardedjedispool , 在 jdeis 里 还有个 jedispool 。这两个的区别:
一个是分片形式 , 可以连接有主备的 Redis 服务端 , 一个是单个的。详细后续学习
3 因为不使用 因为不使用 因为不使用 因为不使用 的封装 的封装 所以自己要自己封装一个 所以自己要自己封装一个 所以自己要自己封装一个 所以自己要自己封装一个
<? xml versión = "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.springframework.org/schema/Jee" xmlns: tx = "http://www.springframework.org/schema/tx" xmlns: aop = "http://www.springframework.org/schema/aop" xsi: schemalocation http://www.springframework.org/schema/Beans/spring-Beanss.xsd http://www.springframework.org/schema/context http://www.springFramework.org/schema/context/spring-conte-contexsd "> ubicación = "classpath: redis.properties" /> <context: component-scan base-package = "com.d.work.main"> < /context: component-scan> <context: component-scan base-pankage = "com.d.work.redis"> < /context: component-scan> <bean id = "jedispolonconfig"> <name de propiedad = "mAxactive" name = "maxidle" valor = "8"/> <propiedad name = "maxwait" value = "1000"/> <propiedad name = "testonBorrow" value = "true"/> <propiedad name = "testonreturn" valor = "true"/> <!-<Property name = "testIlLeidle" value = "true"/>-> </bean> <bean Id = "shardededishededsishededed" sCope " <constructor-arg index = "0" ref = "jediscoolconfig" /> <constructor-arg index = "1"> <list> <reman> <constructor-arg name = "host" valor = "$ {redis.host}" /> <constructor-arg name = "port" value = "$ {redis.port}" /> <constructor-arg nameout " value = "$ {redis.timeout}"/> <constructor-arg name = "weight" value = "1"/> </bean> </list> </constructor-arg> </bean> </beans>RedisDataSource: 定义三个方法
interfaz pública redisdataSource {public abstract shardedjedis getRedisclient (); Public void Returnresource (Shardedjedis Shardedjedis); Public void Returnresource (Shardedjedis Shardedjedis, Boolean Break);}实现 RedisDataSource:
1, 注入配置好的 ShardedJedispool , : :
@Repository ("RedisDataSource") clase pública RedisDataSourceImpl implementa redisDataSource {private static final logger log = loggerFactory.getLogger (redisdataSourceImpl.class); @AUTOWIRED SHARDEDJEDJEDISHEOL SHARDEDJEDISPOOL; public shardedjedis getRedIsClient () {try {shardedjedis shardjedis = shardedjedispool.getResource (); regresar shardjedis; } catch (Exception e) {log.error ("error getRediSclent", e); } return null; } public void returnresource (Shardedjedis Shardedjedis) {shardedjedispool.returnResource (shardedjedis); } public void Returnresource (Shardedjedis Shardedjedis, Boolean Break) {if (roto) {shardedjedispool.returnbreakenResource (shardedjedis); } else {shardedjedispool.returnResource (shardedjedis); }}}: : RedisclientTemplate , 例子实现了放值和取值。最后代码提供了全部命令的实现。
代码就是映射性质的又一次调用 Jedis 的方法而已 , 用了个 roto 来做标示符 决定返还资源的方式。 决定返还资源的方式。
这一层的目的主要也是让再上层的调用不需要关心 Piscina 中链接的取得和返还问题了。
@Repository ("RedIsClientTemplate") clase pública redisclienttemplate {private static final logger log = loggerFactory.getLogger (redisclienttemplate.class); @Autowired privado RedisDataSource RedisDataSource; public void disconnect () {shardedjedis shardedjedis = redisdataSource.getedisClient (); shardedjedis.disconnect (); } / ** * 设置单个值 * * @param Key * @param value * @return * / public string set (clave de cadena, valor de cadena) {string result = null; Shardedjedis shardedjedis = redisdataSource.getedisClient (); if (shardedJedis == null) {resultado return; } boolean roto = falso; intente {resultado = shardedJedis.set (clave, valor); } catch (excepción e) {log.error (e.getMessage (), e); roto = verdadero; } Finalmente {redisdataSource.returnResource (shardedjedis, roto); } resultado de retorno; } / ** * 获取单个值 * * @param clave * @return * / public string get (key de cadena) {string dultin = null; Shardedjedis shardedjedis = redisdataSource.getedisClient (); if (shardedJedis == null) {resultado return; } boolean roto = falso; intente {result = shardedjedis.get (clave); } catch (excepción e) {log.error (e.getMessage (), e); roto = verdadero; } Finalmente {redisdataSource.returnResource (shardedjedis, roto); } resultado de retorno; }}测试代码 :
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
以上就是本文的全部内容 , 希望对大家的学习有所帮助 也希望大家多多支持武林网。 也希望大家多多支持武林网。