以SpringMVC框架为中心疯狂扩展-09、添加Redis依赖

本文详细介绍如何将Spring框架与Redis数据库进行整合,包括配置Redis服务器、引入相关依赖、配置Jedis连接池、创建Redis操作类及其实现,并演示了简单的CRUD操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、配置好Redis服务器并启动Redis

2、增加Redis相关的依赖到pom

		<!-- Redis -->
		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-redis</artifactId>
			<version>1.7.2.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>redis.clients</groupId>
			<artifactId>jedis</artifactId>
			<version>2.9.0</version>
		</dependency>
3、配置jedis

<?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:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx"
	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-4.1.xsd
     http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd">

	<!-- 引入配置文件 其中order属性代表其加载顺序,而ignoreUnresolvablePlaceholders为是否忽略不可解析的Placeholder,如配置了多个PropertyPlaceholderConfigurer,则需设置为true -->
	<bean id="propertyConfigurerJedis"
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="order" value="2" />
		<property name="ignoreUnresolvablePlaceholders" value="true" />
		<property name="location">
			<value>classpath:redis.properties</value>
		</property>
	</bean>

	<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
		<property name="maxIdle" value="${redis.maxIdle}" />
		<property name="minIdle" value="${redis.minIdle}" />
		<property name="maxTotal" value="${redis.maxTotal}" />
		<property name="maxWaitMillis" value="${redis.maxWaitMillis}" />
		<property name="testOnBorrow" value="${redis.testOnBorrow}" />
	</bean>

	<bean id="jedisConnectionFactory"
		class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
		<property name="hostName" value="${redis.host}" />
		<property name="port" value="${redis.port}" />
		<property name="password" value="${redis.password}" />
		<property name="database" value="${redis.default.db}"/>
		<constructor-arg index="0" ref="jedisPoolConfig" />
	</bean>

	<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
		<property name="connectionFactory" ref="jedisConnectionFactory" />
	</bean>
</beans>

#redis的服务器地址
redis.host=192.168.1.100
#redis的服务端口
redis.port=6379
#最大空闲数
redis.maxIdle=100
#最小空闲数
redis.minIdle=0
#链接数据库
redis.default.db=0
#最大连接数
redis.maxTotal=600
#最大建立连接等待时间
redis.maxWaitMillis=1000
#指明是否在从池中取出连接前进行检验,如果检验失败,则从池中去除连接并尝试取出另一个
redis.testOnBorrow=true
#权限
redis.password=123456

4、新增一个rediuis操作的类

import com.syx.customer.model.UserModel;

/** 
 * 用户Dao接口 Redis
 *
 * @author sunyx 
 * @since JDK 1.8 
 */
public interface UserDao {
	
    /**    
     * 新增用户到Redis 
     * 
     * @author sunyx 
     * @param user
     * @return 
     * @since JDK 1.8  
     */ 
    boolean add(UserModel user); 
    
    /**    
     * 根据userid获取UserModel  
     *
     * @author sunyx 
     * @param keyId
     * @return 
     * @since JDK 1.8  
     */ 
    UserModel get(String keyId);
}

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Component;

import com.syx.customer.dao.UserDao;
import com.syx.customer.model.UserModel;

/** 
 * userDao接口实现类,操作redis    
 *
 * @author sunyx 
 * @since JDK 1.8 
 */
@Component("userDao")
public class UserDaoImpl implements UserDao {
	
	@Autowired
    protected RedisTemplate<String,UserModel> redisTemplate;  

	public boolean add(final UserModel user) {
		final boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {  
            public Boolean doInRedis(RedisConnection connection)  
                    throws DataAccessException {  
            	//获取 RedisSerializer 
                //keySerializer:这个是对key的默认序列化器。默认值是StringSerializer。
            	//valueSerializer:这个是对value的默认序列化器,默认值是取自DefaultSerializer的JdkSerializationRedisSerializer。
            	//hashKeySerializer:对hash结构数据的hashkey序列化器,默认值是取自DefaultSerializer的JdkSerializationRedisSerializer。
            	//hashValueSerializer:对hash结构数据的hashvalue序列化器,默认值是取自DefaultSerializer的JdkSerializationRedisSerializer。
                final RedisSerializer<String> serializer = redisTemplate.getStringSerializer();  
                final byte[] key  = serializer.serialize(user.getId());  
                final byte[] name = serializer.serialize(user.getName());  
                return connection.setNX(key, name);  
            }  
        });  
        return result; 
	}
	
    public UserModel get(final String keyId) {  
    	final UserModel result = redisTemplate.execute(new RedisCallback<UserModel>() {  
            public UserModel doInRedis(RedisConnection connection)  
                    throws DataAccessException {  
                final RedisSerializer<String> serializer = redisTemplate.getStringSerializer();  
                final byte[] key = serializer.serialize(keyId);
                final byte[] value = connection.get(key);  
                if (value == null) {  
                    return null;  
                }  
                final String name = serializer.deserialize(value);  
                return new UserModel(keyId,name);  
            }  
        });  
        return result;  
    }  
	
}
/** 
 * 简单业务逻辑的实现类
 *
 * @author sunyx 
 * @since JDK 1.8 
 */
@Service("simpleService")
public class SimpleServiceImpl implements SimpleService {
	
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private UserDao userDao;

	public String put(String userId) {
		final UserModel userModel = userMapper.findUserById(userId);
		userDao.add(userModel);
		return "ok";
	}

	public void get(String userId) {
		final UserModel user = userDao.get(userId);
		System.out.println(user.getId()+","+user.getName());
	}

}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.syx.customer.service.SimpleService;

/** 
 * redis Controller类     
 *
 * @author sunyx 
 * @since JDK 1.8 
 */
@Controller
@RequestMapping("/redis")
public class RedisController{	
	@Autowired
	private SimpleService simpleService;
	
	@RequestMapping("/put")
    public String put(){
		simpleService.put("1");
        return "put";
    }
	
	@RequestMapping("/get")
	public String get(){
		simpleService.get("1");
		return "get";
	}
}
重启服务

通过/put设置值到redis

通过/get可以过去到redis中的值




异常1:Cannot get Jedis connection; nested exception is redis.clients.jedis.exceptions.JedisConnectionException: Could not get a resource from the pool

解决:

1、通过 redis.conf 查看bind 127.0.0.1 是否被注释掉了,如果没有被注释掉就将其注释掉,不然就只能被绑定的ip访问;也可以添加一个新的ip既需要访问的ip绑定进去。


2、设置auth

2.1通过命令设置

redis-cli
AUTH 123456
如果报错
CONFIG SET requirepass 123456
AUTH 123456
如果服务重启,auth就失效了。如果要长期使用,就需要在redis.conf 中设置

2.2在redis.conf 中设置

vi redis.conf
/requirepass
找到
#requirepass foobar
新增
requirepass 123456
退出vi 用redis.config配置启动redis
redis.server ../redis.config



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值