详解java之redis篇(spring

网友投稿 204 2023-06-19


详解java之redis篇(spring

1,利用spring-data-redis整合

项目使用的pom.xml:

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

4.0.0</modelVersion>

com.x.redis

Spring_redis

1.0-SNAPSHOT

jar

Spring_redis

http://maven.apache.org

UTF-8

org.springframework.data

spring-data-redis

1.0.2.RELEASE

org.springframework

spring-core

3.1.2.RELEASE

redis.clients

jedis

2.1.0

junit

junit

4.8.2

test

org.slf4j

slf4j-api

1.6.1

org.slf4j

jcl-over-slf4j

1.6.1

commons-logging

commons-logging

1.1.1

provided

ch.qos.logback

logback-classic

0.9.24

runtime

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

4.0.0</modelVersion>

com.x.redis

Spring_redis

1.0-SNAPSHOT

jar

Spring_redis

http://maven.apache.org

UTF-8

org.springframework.data

spring-data-redis

1.0.2.RELEASE

org.springframework

spring-core

3.1.2.RELEASE

redis.clients

jedis

2.1.0

junit

junit

4.8.2

test

org.slf4j

slf4j-api

1.6.1

org.slf4j

jcl-over-slf4j

1.6.1

commons-logging

commons-logging

1.1.1

provided

ch.qos.logback

logback-classic

0.9.24

runtime

除了log部分,只有一个spring core 和 spring-data-redis了

项目文件目录结构:

applicationContext.xml:

1,context:property-placeholder 标签用来导入properties文件。从而替换${redis.maxIdle}这样的变量。

2,context:component-scan 是为了在com.x.redis.dao报下的类能够实用spring的注解注入的方式。

3,事实上我们只需要把JedisPoolConfig配数来就好了,接下来就是spring的封装了。所以直接看UserDAOImpl的实现就明白了。

xmlns:xsi="http://w3.org/2001/XMLSchema-instance" xmlns:p="http://springframework.org/schema/p"

xmlns:context="http://springframework.org/schema/context"

xmlns:jee="http://springframework.org/schema/jee" xmlns:tx="http://springframework.org/schema/tx"

xmlns:aop="http://springframework.org/schema/aop"

xsi:schemaLocation="

http://springframework.org/schema/beans http://springframework.org/schema/beans/spring-beans.xsd

http://springframework.org/schema/context http://springframework.org/schema/context/spring-context.xsd">

p:host-name="${redis.host}" p:port="${redis.port}" p:password="${redis.pass}" p:pool-config-ref="poolConfig"/>

xmlns:xsi="http://w3.org/2001/XMLSchema-instance" xmlns:p="http://springframework.org/schema/p"

xmlns:context="http://springframework.org/schema/context"

xmlns:jee="http://springframework.org/schema/jee" xmlns:tx="http://springframework.org/schema/tx"

xmlns:aop="http://springframework.org/schema/aop"

xsi:schemaLocation="

http://springframework.org/schema/beans http://springframework.org/schema/beans/spring-beans.xsd

http://springframework.org/schema/context http://springframework.org/schema/context/spring-context.xsd">

p:host-name="${redis.host}" p:port="${redis.port}" p:password="${redis.pass}" p:pool-config-ref="poolConfig"/>

p:host-name="${redis.host}" p:port="${redis.port}" p:password="${redis.pass}" p:pool-config-ref="poolConfig"/>

redis.properties:

# Redis settings

#redis.host=192.168.20.101

#redis.port=6380

#redis.pass=foobared

redis.host=127.0.0.1

redis.port=6379

redis.pass=

redis.maxIdle=300

redis.maxActive=600

redis.maxWait=1000

redis.testOnBorrow=true

UserDAOImpl:

1,spring对dao层的封装很多用了类似于下面代码的模板方式。

2,RedisTemplate就是spring对redis的一个封装而已。

public class UserDAOImpl implements UserDAO {

@Autowired

protected RedisTemplate redisTemplate;

public void saveUser(final User user) {

redisTemplate.execute(new RedisCallback() {

@Override

public Object doInRedis(RedisConnection connection) throws DataAccessException {

connection.set(redisTemplate.getStringSerializer().serialize("user.uid." + user.getId()),

redisTemplate.getStringSerializer().serialize(user.getName()));

return null;

}

});

}

@Override

public User getUser(final long id) {

return redisTemplate.execute(new RedisCallback() {

@Override

public User doInRedis(RedisConnection connection) throws DataAccessException {

byte[] key = redisTemplate.getStringSerializer().serialize("user.uid." + id);

if (connection.exists(key)) {

byte[] value = connection.get(key);

String name = redisTemplate.getStringSerializer().deserialize(value);

User user = new User();

user.setName(name);

user.setId(id);

return user;

}

return null;

}

});

}

}

其他:

User:

public class User {

private long id;

private String name;

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) {

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,不利用spring-data-redis整合

个人觉得这样整合灵活度更大,能够更加明了的完成任务。

pom.xml:

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

4.0.0

com.d.work

Redis_Templete

1.0-SNAPSHOT

jar

Redis_Templete

http://maven.apache.org

UTF-8

junit

junit

3.8.1

test

redis.clients

jedis

2.1.0

org.springframework

spring-core

3.1.2.RELEASE

org.springframework

spring-beans

3.1.2.RELEASE

org.springframework

spring-context

3.1.2.RELEASE

org.slf4j

slf4j-api

1.6.1

org.slf4j

jcl-over-slf4j

1.6.1

commons-logging

commons-logging

1.1.1

provided

ch.qos.logback

logback-classic

0.9.24

runtime

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

4.0.0

com.d.work

Redis_Templete

1.0-SNAPSHOT

jar

Redis_Templete

http://maven.apache.org

UTF-8

junit

junit

3.8.1

test

redis.clients

jedis

2.1.0

org.springframework

spring-core

3.1.2.RELEASE

org.springframework

spring-beans

3.1.2.RELEASE

org.springframework

spring-context

3.1.2.RELEASE

org.slf4j

slf4j-api

1.6.1

org.slf4j

jcl-over-slf4j

1.6.1

commons-logging

commons-logging

1.1.1

provided

ch.qos.logback

logback-classic

0.9.24

runtime

目录结构:

data-source.xml

1,context:property-placeholder 和 context:component-scan 前面解释过啦。

2,配置了一个ShardedJedisPool,在jdeis里 还有个JedisPool。这两个的区别:

一个是分片形式,可以连接有主备的redis服务端,一个是单个的。详细后续学习

3,因为不使用spring-data-redis的封装,所以自己要自己封装一个

xmlns:xsi="http://w3.org/2001/XMLSchema-instance" xmlns:p="http://springframework.org/schema/p"

xmlns:context="http://springframework.org/schema/context"

xmlns:jee="http://springframework.org/schema/jee" xmlns:tx="http://springframework.org/schema/tx"

xmlns:aop="http://springframework.org/schema/aop"

xsi:schemaLocation="

http://springframework.org/schema/beans http://springframework.org/schema/beans/spring-beans.xsd

http://springframework.org/schema/context http://springframework.org/schema/context/spring-context.xsd">

xmlns:xsi="http://w3.org/2001/XMLSchema-instance" xmlns:p="http://springframework.org/schema/p"

xmlns:context="http://springframework.org/schema/context"

xmlns:jee="http://springframework.org/schema/jee" xmlns:tx="http://springframework.org/schema/tx"

xmlns:aop="http://springframework.org/schema/aop"

xsi:schemaLocation="

http://springframework.org/schema/beans http://springframework.org/schema/beans/spring-beans.xsd

http://springframework.org/schema/context http://springframework.org/schema/context/spring-context.xsd">

RedisDataSource:定义三个方法

public interface RedisDataSource {

public abstract ShardedJedis getRedisClient();

public void returnResource(ShardedJedis shardedJedis);

public void returnResource(ShardedJedis shardedJedis,boolean broken);

}

实现redisDataSource:

1, 注入配置好的ShardedJehttp://disPool,这三个方法的作用:

getRedisClient() : 取得redis的客户端,可以执行命令了。

returnResource(ShardedJedis shardedJedis) : 将资源返还给pool

returnResource(ShardedJedis shardedJedis, boolean broken) : 出现异常后,将资源返还给pool (其实不需要第二个方法)

@Repository("redisDataSource")

public class RedisDataSourceImpl implements RedisDataSource {

private static final Logger log = LoggerFactory.getLogger(RedisDataSourceImpl.class);

@Autowired

private ShardedJedisPool shardedJedisPool;

public ShardedJedis getRedisClient() {

try {

ShardedJedis shardJedis = shardedJedisPool.getResource();

return 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 broken) {

if (broken) {

shardedJedisPool.returnBrokenResource(shardedJedis);

} else {

shardedJedisPool.returnResource(shardedJedis);

}

}

}

第二层的封装:RedisClientTemplate,例子实现了放值和取值。最后代码提供了全部命令的实现。

代码就是映射性质的又一次调用jedis的方法而已,用了个broken来做标示符,决定返还资源的方式。

这一层的目的主要也是让再上层的调用不需要关心pool中链接的取得和返还问题了。

@Repository("redisClientTemplate")

public class 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(String key, String value) {

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);

broken = true;

} finally {

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);

broken = true;

} finally {

redisDataSource.returnResource(shardedJedis, broken);

}

return result;

}

}

测试代码:

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.jb51.net/201701/yuanma/RedisClientTemplate_jb51.rar


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:微信小程序 实战程序简易新闻的制作
下一篇:图片验证码概述及实现步骤
相关文章

 发表评论

暂时没有评论,来抢沙发吧~