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.sourcencoding> </souperties> <pendências> <Pusency> <vroupid> org.springfamework.data <TeRtifactId> Spring-Data-Redis </ArtifactId> <Versão> 1.0.2.Release </siers> </dependency> <pendency> <puperid> org.springframework </frugId> <sutifactId> spring-core </stifactId> <siers> 3.1 GroupLeease </sipers> </dependência> </Dependência <artifactId>jedis</artifactId> <version>2.1.0</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.8.2</version> <scope>test</scope> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.6.1</version> </dependency> <!-- 将现有的jakarta commons logging的调用转换成lsf4j的调用。 --> <dependency> <groupId>org.slf4j</groupId> <artifactId>jcl-over-slf4j</artifactId> <version>1.6.1</version> </dependency> <!-Hack: 确保 Commons-Logging 的 jar 包不被引入 , 否则将和 jcl-over-slf4j 冲突-> <pendence> <puperid> commons-logging </foupid> <stifactId> Commons-Logging </ArtifactId> <sipers> 1.1.1 </versão> <Cope> fornecido </scope> </dependência> Slf4j 的实现: Logback , 用来取代 log4j 。更快、更强!-> <pendence> <puperiD> ch.qos.logback </groupiD> <TRAFACTID> logback-Classic </ArtifactId> <Versão> 0.9.24 </versão> <Cope> </scope> </dependência> </dependências> </Project>
除了 log 部分 , 只有一个 núcleo da mola 和 Spring-Data-Redis 了
项目文件目录结构
ApplicationContext.xml:
1 , Contexto: Propriedade-Placa-Place 标签用来导入 Propriedades 文件。从而替换 $ {Redis.maxidle} 这样的变量。
2 , Contexto: componente-scan 是为了在 com.x.redis.dao 报下的类能够实用 mola 的注解注入的方式。
3 , 事实上我们只需要把 JedispoolConfig 配数来就好了 , 接下来就是 Spring 的封装了。所以直接看 Userdaoimpl 的实现就明白了。
<? xml versão = "1.0" coding = "utf-8"?> <Beans xmlns = "http://www.springframework.org/schema/beans" xmlns: xsi = "http:/wwww.w3 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 http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:property-placeholder Local = "ClassPath: Redis.Properties" /> <Contexto: componente-Scan Base-Package = "com.x.redis.dao"> < /context: component-scan> <bean id = "poolconfig"> <propriedades name = "maxidle" value = "$ {Redis.Maxidle}" /> <nome da propriedade = "maxidle" "MAXIDLE =" $ {Redis.Maxidle} " /> <nome da propriedade =" maxidle "" ") name = "maxwait" value = "$ {Redis.maxwait}" /> <propriedade name = "testonborrow" value = "$ {Redis.testonborrow}" /> < /bean> <bean id = "ConnectionFactory" p: host-name = "$ {Redis.host}" P: port = "$ {" { P: Pool-config-ref = "poolconfig"/> <bean id = "redistemplate"> <propriedade name = "ConnectionFactory" ref = "ConnectionFactory"/> </shean> <bean id = "userdao"/> </ Beans> Redis.Properties:
#Redis Settings#Redis.Host = 192.168.20.101#Redis.port = 6380#Redis.pass = Foobaredredis.Host = 127.0.0.1redis.port = 6379ReRiS.pass = Redis.Maxidle = 300Redis.Maxactive = 600RoMis.MaxWait = Maxidle = 300Redis.Maxactive = 600RoMis.Maxwait = Maxidle = 300Redis.Maxactive = 600Reous.Maxwait = MAXWAAT = 100ReaxIdis.MaxWait = 100ReDis.Maxactive = 600Reougus.Maxwait = 100.
Userdaoimpl:
1 , primavera 对 Dao 层的封装很多用了类似于下面代码的模板方式。
2 , Redistemplate 就是 Spring 对 Redis 的一个封装而已。
classe pública userDaoImpl implementa Userdao {@AUTOWIRED REDISTEMPLATE protegido <serializável, serializável> redistemplate; public void saveUser (usuário final do usuário) {redistemplate.execute (new Rediscallback <Beject> () {@Override public Object doinredis (conexão de redisconnection) lança dataAccessException {Connection.Set (Redistemplate.getStringSerializer (). redistemplate.getStringSerializer (). Serialize (user.getName ()); } @Override Public User GetUser (Final Long Id) {return redistemplate.execute (novo Rediscallback <suser> () {@Override Public User Doinredis (Redisconnection Connection) lança dataAccessException {Byte [] key = Redistemplate.getSterriDerizer (). = conexão. }}其他
Usuário:
Public Class User {Private Long ID; nome de string privado; public Long getId () {return id; } public void setId (longo id) {this.id = id; } public string getName () {return name; } public void setName (nome da string) {this.name = name; }}测试代码
public static void main (string [] args) {ApplicationContext AC = new ClassPathXMLApplicationContext ("ClassPath: /ApplicationContext.xml"); Userdao userdao = (userdao) ac.getbean ("userdao"); Usuário do usuário1 = novo usuário (); user1.setId (1); user1.setName ("Obama"); userdao.saveUser (user1); Usuário usuário2 = 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> <name>Redis_Templete</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>junit</groupId> <TRAFACTID> JUNIT </STIFACTID> <Versão> 3.8.1 </siers> <cope> Test </scope> </dependency> <pendencency> <voupid> redis.clients </groupid> <stifactId> jedis </stifactId> <versão> 2.1.0 </versão> </dependência> <pendency> </groupwork> <TeRtifactId> Spring-core </stifactId> <versão> 3.1.2.Release </sisters> </dependency> <pendency> <voundid> org.springframework </groupiD> <TorfactId> Spring-Beans </ArtifactId> <Versão> 3.1.Release </Version> </Dependência> </dependência> </dependência> </dependência> </sorfactId> <versão> 3 3.1. <TeRtifactId> Spring-Context </ArtifactId> <versão> 3.1.2.Release </sipers> </dependency> <pendency> <puperid> org.slf4j </frupId> <ArtifactId> slf4j-api </stifactid> <bers> 1.6.1 </vers) <! <dependency> <groupId>org.slf4j</groupId> <artifactId>jcl-over-slf4j</artifactId> <version>1.6.1</version> </dependency> <!-- Hack:确保commons-logging的jar包不被引入,否则将和jcl-over-slf4j冲突 --> <dependency> <groupId>commons-logging</groupId> </artifactId> 1.1.1 </version> <cope> fornecido </scope> </dependency> <!-slf4j 的实现: Logback , 用来取代 log4j 。更快、更强!-> <pendency> <puidid> ch.qos.Logback </GroupId> <artefactId2) <sermsiSshiD2) <cope> Runtime </cope> </dependency> </dependências> </project>
目录结构
data-source.xml
1 , Contexto: Propriedade-Placa-Place 和 Contexto: Scan componente 前面解释过啦。
2 , 配置了一个 shardedjedispool , Jdeis 里 Jedispool 。这两个的区别:
一个是分片形式 , 可以连接有主备的 Redis 服务端 , 一个是单个的。详细后续学习
3 , 因为不使用 Spring-Data-Redis 的封装 , 所以自己要自己封装一个
<? xml versão = "1.0" coding = "utf-8"?> <Beans xmlns = "http://www.springframework.org/schema/beans" xmlns: xsi = "http:/wwww.w3 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 http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:property-placeholder Local = "Classpath: Redis.Properties" /> <Contexto: componente-Scan Base-Package = "com.d.work.main"> < /context: component-scan> <Contexto: component-scan Base-Package = "com.d.d.work.redis"> < /context: component-scan> <boean ID = "JEDISCOLCONCIG"> < /Context-scan name = "maxidle" value = "8"/> <propriedade name = "maxwait" value = "1000"/> <propriedade name = "testOnBorrow" value = "true"/> <names name = "testOnReturn" value = "true"/> <!-name = "testwhileidle" = "true"/>-> </ * </> <! <construtor-arg index = "0" ref = "jedispoolconfig" /> <construtor-arg index = "1"> <lista> <ipean> <construtor-arg name = "host" value = "$ {Redis.host}" /> <construtor-arg name = "Port" = "$ {{{ value = "$ {Redis.Timeout}"/> <construtor-arg name = "weight" value = "1"/> </i bean> </list> </construtor-arg> </shean> </beans>RedisDatasource: 定义三个方法
interface pública redisdataSource {public abstract shardedjedis getredisclient (); public void ReturnResource (shardedjedis shardedjedis); public void ReturnResource (shardedjedis shardedjedis, booleano quebrado);}实现 RedisDataSource:
1, 注入配置好的 shardedjedispool , 这三个方法的作用 ::
@Repository ("RedisDataSource") Classe pública RedisDataSourceImpl implementa RedisDataSource {private estático final logger Log = LoggerFactory.getLogger (RedisDataSourceImpl.class); @Autowired Private Shardedjedispool shardedjedispool; public shardedjedis getRredIllient () {try {shardedjedis shardjedis = shardedjedispool.getResource (); retornar Shardjedis; } catch (Exceção e) {Log.error ("Erro GetredisClent", e); } retornar nulo; } public void ReturnResource (shardedjedis shardedjedis) {shardedjedispool.returnResource (shardedjedis); } public void ReturnResource (shardedjedis shardedjedis, booleano quebrado) {if (quebrado) {shardedjedispool.returnbrokenResource (shardedjedis); } else {shardedjedispool.returnResource (shardedjedis); }}}第二层的封装 : RedIclientTemplate , 例子实现了放值和取值。最后代码提供了全部命令的实现。
Jedis 的方法而已 , 用了个 quebrado 来做标示符 , 决定返还资源的方式。
这一层的目的主要也是让再上层的调用不需要关心 Piscina 中链接的取得和返还问题了。
@Repository ("RedisclientTemplate") Classe public RedIclientTemplate {Private Static Final Logger Log = LoggerFactory.getLogger (RedIclientTemplate.class); @Autowired Private RedisDataSource RedisDataSource; public void desconect () {shardedjedis shardedjedis = redisdataSource.getRedIclient (); shardedjedis.disconnect (); } / ** * 设置单个值 * * @param key * @param value * @return * / public string set (tecla String, string value) {string resultado = null; Shardedjedis shardedjedis = redisdataSource.getRedInClient (); if (shardedjedis == null) {return resultado; } booleano quebrado = false; tente {resultado = shardedjedis.set (chave, valor); } catch (Exceção e) {log.error (e.getMessage (), e); quebrado = true; } finalmente {redisdataSource.returnResource (shardedjedis, quebrado); } resultado de retorno; } / ** * 获取单个值 * * @param key * @return * / public string get (string key) {string resultado = null; Shardedjedis shardedjedis = redisdataSource.getRedInClient (); if (shardedjedis == null) {return resultado; } booleano quebrado = false; tente {resultado = shardedjedis.get (chave); } catch (Exceção e) {log.error (e.getMessage (), e); quebrado = true; } finalmente {redisdataSource.returnResource (shardedjedis, quebrado); } resultado de retorno; }}测试代码
public static void main (string [] args) {ApplicationContext AC = new ClassPathXMLApplicationContext ("ClassPath: /data-source.xml"); RedIclientTemplate redisclient = (RedIclientTemplate) AC.GetBean ("RedIclientTemplate"); redistlient.set ("A", "ABC"); System.out.println (redisclient.get ("a")); }附上 RedIclientTemplate 全部实现:
RedIclientTemplate 代码太多 , :: http: //xiazai.vevb.com/201701/yuanma/rediscienttemplate_jb51.rar
以上就是本文的全部内容 , 希望对大家的学习有所帮助 , 也希望大家多多支持武林网。