Spring-redis整合的配置文件

1.applicationContext.xml

<?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" 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.3.xsd">


	<context:component-scan base-package="com.znsd.redis.utils" />


	<!--1,如果你有多个数据源需要通过<context:property-placeholder管理,且不愿意放在一个配置文件里,那么一定要加上ignore-unresolvable=“true" -->
	<context:property-placeholder location="classpath:redis.properties" ignore-unresolvable="true" />

	<!--2,注意新版本2.3以后,JedisPoolConfig的property name,不是maxActive而是maxTotal,而且没有maxWait属性,建议看一下Jedis源码或百度。 -->
	<!-- redis连接池配置 -->
	<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
		<!--最大空闲数 -->
		<property name="maxIdle" value="${redis.maxIdle}" />
		<!--连接池的最大数据库连接数 -->
		<property name="maxTotal" value="${redis.maxTotal}" />
		<!--最大建立连接等待时间 -->
		<property name="maxWaitMillis" value="${redis.maxWaitMillis}" />
		<!--逐出连接的最小空闲时间 默认1800000毫秒(30分钟) -->
		<property name="minEvictableIdleTimeMillis" value="${redis.minEvictableIdleTimeMillis}" />
		<!--每次逐出检查时 逐出的最大数目 如果为负数就是 : 1/abs(n), 默认3 -->
		<property name="numTestsPerEvictionRun" value="${redis.numTestsPerEvictionRun}" />
		<!--逐出扫描的时间间隔(毫秒) 如果为负数,则不运行逐出线程, 默认-1 -->
		<property name="timeBetweenEvictionRunsMillis" value="${redis.timeBetweenEvictionRunsMillis}" />
	</bean>

	<!--redis连接工厂 -->
	<bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" destroy-method="destroy">
		<property name="poolConfig" ref="jedisPoolConfig"></property>
		<!--IP地址 -->
		<property name="hostName" value="${redis.host.ip}"></property>
		<!--端口号 -->
		<property name="port" value="${redis.port}"></property>
		<!--如果Redis设置有密码 -->
		<!-- <property name="password" value="${redis.password}" /> -->
		<!--客户端超时时间单位是毫秒 -->
		<property name="timeout" value="${redis.timeout}"></property>
	</bean>

	<!-- redis操作模板,这里采用尽量面向对象的模板 -->
	<bean id="jedisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
		<property name="connectionFactory" ref="jedisConnectionFactory" />
		<!-- 指定redis中key-value的序列化方式 -->
		<property name="keySerializer">
			<bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />
		</property>
		<property name="valueSerializer">
			<bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />
		</property>
	</bean>

	<!--redis工具类 (也可以通过注解的方式注入) -->
	<!-- <bean id="redisUtil" class="com.znsd.redis.util.RedisTemplateUtil"> <property name="redisTemplate" ref="redisTemplate" /> </bean> -->



</beans>

2.redis配置文件redis.properties

#ip\u5730\u5740
redis.host.ip=19.11.82.111
#\u7AEF\u53E3\u53F7  
redis.port=6379  
#\u5982\u679C\u6709\u5BC6\u7801  
redis.password=  
#\u5BA2\u6237\u7AEF\u8D85\u65F6\u65F6\u95F4\u5355\u4F4D\u662F\u6BEB\u79D2 \u9ED8\u8BA4\u662F2000  
redis.timeout=3000  

#\u6700\u5927\u7A7A\u95F2\u6570  
redis.maxIdle=6  
#\u8FDE\u63A5\u6C60\u7684\u6700\u5927\u6570\u636E\u5E93\u8FDE\u63A5\u6570\u3002\u8BBE\u4E3A0\u8868\u793A\u65E0\u9650\u5236,\u5982\u679C\u662Fjedis 2.4\u4EE5\u540E\u7528redis.maxTotal  
#redis.maxActive=600  
#\u63A7\u5236\u4E00\u4E2Apool\u53EF\u5206\u914D\u591A\u5C11\u4E2Ajedis\u5B9E\u4F8B,\u7528\u6765\u66FF\u6362\u4E0A\u9762\u7684redis.maxActive,\u5982\u679C\u662Fjedis 2.4\u4EE5\u540E\u7528\u8BE5\u5C5E\u6027  
redis.maxTotal=20  
#\u6700\u5927\u5EFA\u7ACB\u8FDE\u63A5\u7B49\u5F85\u65F6\u95F4\u3002\u5982\u679C\u8D85\u8FC7\u6B64\u65F6\u95F4\u5C06\u63A5\u5230\u5F02\u5E38\u3002\u8BBE\u4E3A-1\u8868\u793A\u65E0\u9650\u5236\u3002  
redis.maxWaitMillis=3000  
#\u8FDE\u63A5\u7684\u6700\u5C0F\u7A7A\u95F2\u65F6\u95F4 \u9ED8\u8BA41800000\u6BEB\u79D2(30\u5206\u949F)  
redis.minEvictableIdleTimeMillis=300000  
#\u6BCF\u6B21\u91CA\u653E\u8FDE\u63A5\u7684\u6700\u5927\u6570\u76EE,\u9ED8\u8BA43  
redis.numTestsPerEvictionRun=4  
#\u9010\u51FA\u626B\u63CF\u7684\u65F6\u95F4\u95F4\u9694(\u6BEB\u79D2) \u5982\u679C\u4E3A\u8D1F\u6570,\u5219\u4E0D\u8FD0\u884C\u9010\u51FA\u7EBF\u7A0B, \u9ED8\u8BA4-1  
redis.timeBetweenEvictionRunsMillis=30000  
  1. spring.xml
<?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:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" 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.2.xsd
   	http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
   	http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd">




</beans>

4.springmvc.xml

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


	<!-- SpringMVC的配置文件,只扫描@Controller和@ControllerAdvice注解修饰的类 -->
	<context:component-scan base-package="com.znsd.redis" use-default-filters="false">
		<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
		<context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice" />
	</context:component-scan>


	<!-- 视图解析器:将逻辑视图转发到对应的物理视图 -->
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/views/" />
		<property name="suffix" value=".jsp" />
	</bean>


	<!-- 直接配置对应的视图访问路径 -->
	<!-- <mvc:view-controller path="/vote_all.html" view-name="vote_all" /> -->
	<!-- <mvc:view-controller path="/index" view-name="index" /> -->


	<!-- 如果配置了mvc-controller会导致其它页面没法正常访问,还需要添加一个标签 -->
	<mvc:annotation-driven />

	<mvc:default-servlet-handler />


	<!-- 自定义视图解析器,使用order来配置优先级,数字越小,优先级越高。 -->
	<!-- <bean class="org.springframework.web.servlet.view.BeanNameViewResolver"> <property name="order" value="1"></property> </bean> -->


</beans>


主要是applicationContext.xml中配置了redis信息

工具类

package com.znsd.redis.utils;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

@Component
public class RedisTemplateUtil<T> {

    @Autowired(required = false)
    public RedisTemplate redisTemplate;
	/**
	 * 缓存基本的对象,Integer、String、实体类等
	 * 
	 * @param key   缓存的键值
	 * @param value 缓存的值
	 * @return 缓存的对象
	 */
	public <T> ValueOperations<String, T> setCacheObject(String key, T value) {

		ValueOperations<String, T> operation = redisTemplate.opsForValue();
		operation.set(key, value);
		return operation;
	}

	/**
	 * 获得缓存的基本对象。
	 * 
	 * @param key       缓存键值
	 * @param operation
	 * @return 缓存键值对应的数据
	 */
	public <T> T getCacheObject(String key/* ,ValueOperations<String,T> operation */) {
		ValueOperations<String, T> operation = redisTemplate.opsForValue();
		return operation.get(key);
	}

	/**
	 * 缓存List数据
	 * 
	 * @param key      缓存的键值
	 * @param dataList 待缓存的List数据
	 * @return 缓存的对象
	 */
	public <T> ListOperations<String, T> setCacheList(String key, List<T> dataList) {
		ListOperations listOperation = redisTemplate.opsForList();
		if (null != dataList) {
			int size = dataList.size();
			for (int i = 0; i < size; i++) {

				listOperation.rightPush(key, dataList.get(i));
			}
		}

		return listOperation;
	}

	/**
	 * 获得缓存的list对象
	 * 
	 * @param key 缓存的键值
	 * @return 缓存键值对应的数据
	 */
	public <T> List<T> getCacheList(String key) {
		List<T> dataList = new ArrayList<T>();
		ListOperations<String, T> listOperation = redisTemplate.opsForList();
		Long size = listOperation.size(key);

		for (int i = 0; i < size; i++) {
			dataList.add((T) listOperation.leftPop(key));
		}

		return dataList;
	}

	/**
	 * 缓存Set
	 * 
	 * @param key     缓存键值
	 * @param dataSet 缓存的数据
	 * @return 缓存数据的对象
	 */
	public <T> BoundSetOperations<String, T> setCacheSet(String key, Set<T> dataSet) {
		BoundSetOperations<String, T> setOperation = redisTemplate.boundSetOps(key);
		/*
		 * T[] t = (T[]) dataSet.toArray(); setOperation.add(t);
		 */

		Iterator<T> it = dataSet.iterator();
		while (it.hasNext()) {
			setOperation.add(it.next());
		}

		return setOperation;
	}

	/**
	 * 获得缓存的set
	 * 
	 * @param key
	 * @param operation
	 * @return
	 */
	public Set<T> getCacheSet(String key/* ,BoundSetOperations<String,T> operation */) {
		Set<T> dataSet = new HashSet<T>();
		BoundSetOperations<String, T> operation = redisTemplate.boundSetOps(key);

		Long size = operation.size();
		for (int i = 0; i < size; i++) {
			dataSet.add(operation.pop());
		}
		return dataSet;
	}

	/**
	 * 缓存Map
	 * 
	 * @param key
	 * @param dataMap
	 * @return
	 */
	public <T> HashOperations<String, String, T> setCacheMap(String key, Map<String, T> dataMap) {

		HashOperations hashOperations = redisTemplate.opsForHash();
		if (null != dataMap) {

			for (Map.Entry<String, T> entry : dataMap.entrySet()) {

				/*
				 * System.out.println("Key = " + entry.getKey() + ", Value = " +
				 * entry.getValue());
				 */
				hashOperations.put(key, entry.getKey(), entry.getValue());
			}

		}

		return hashOperations;
	}

	/**
	 * 获得缓存的Map
	 * 
	 * @param key
	 * @param hashOperation
	 * @return
	 */
	public <T> Map<String, T> getCacheMap(String key/* ,HashOperations<String,String,T> hashOperation */) {
		Map<String, T> map = redisTemplate.opsForHash().entries(key);
		/* Map<String, T> map = hashOperation.entries(key); */
		return map;
	}

	/**
	 * 缓存Map
	 * 
	 * @param key
	 * @param dataMap
	 * @return
	 */
	public <T> HashOperations<String, Integer, T> setCacheIntegerMap(String key, Map<Integer, T> dataMap) {
		HashOperations hashOperations = redisTemplate.opsForHash();
		if (null != dataMap) {

			for (Map.Entry<Integer, T> entry : dataMap.entrySet()) {

				/*
				 * System.out.println("Key = " + entry.getKey() + ", Value = " +
				 * entry.getValue());
				 */
				hashOperations.put(key, entry.getKey(), entry.getValue());
			}

		}

		return hashOperations;
	}

	/**
	 * 获得缓存的Map
	 * 
	 * @param key
	 * @param hashOperation
	 * @return
	 */
	public <T> Map<Integer, T> getCacheIntegerMap(String key/* ,HashOperations<String,String,T> hashOperation */) {
		Map<Integer, T> map = redisTemplate.opsForHash().entries(key);
		/* Map<String, T> map = hashOperation.entries(key); */
		return map;
	}
}

工具少点的工具类

package com.znsd.redis.utils;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;

/** 
 * 
 * @项目名称:common
 * @类名称:RedisUtil
 * @类描述:基于spring和redis的redisTemplate工具类;
 * @创建人:wyait
 * @创建时间:2017年12月8日 下午3:32:38 
 * @version:V1.0
 */
// @Component
public class RedisUtil {
    // 通过构造方法注入
    // @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /*
     * 如果使用注解注入RedisTemplate对象,则不需要该setter方法
     */
    public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    /** 
     * String类型缓存获取 
     * @param key 键 
     * @return 值 
     */
    public Object get(String key) {
        return key == null ? null : redisTemplate.opsForValue().get(key);
    }

    /** 
     * String类型缓存保存 
     * @param key 键 
     * @param value 值 
     * @return true:成功;false:失败 
     */
    public boolean set(String key, Object value) {
        try {
            if (StringUtils.isNotEmpty(key) && null != value) {
                redisTemplate.opsForValue().set(key, value);
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

   // ... ...

}

我的controller

package com.znsd.redis.controllers;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.znsd.redis.utils.RedisTemplateUtil;

@Controller
public class IndexController {

	@Resource
	private RedisTemplateUtil<Map<String, String>> redisCache;

	@RequestMapping("/index")
	public String index() {

		Map<String, String> examMap = new HashMap<>();
		examMap.put("title", "hello1");
		examMap.put("options", "hel23424332lo1");
		examMap.put("right", "hello2343241");
		examMap.put("joinId", "hello23421");
		examMap.put("answer", "hello234");

		System.out.println(redisCache.setCacheMap("redistest", examMap));

		Map<String, String> map = redisCache.getCacheMap("redistest");

		for (String s : map.keySet()) {
			System.out.println(s);
			System.out.println(map.get(s));
		}

		return "index";
	}

}

web.xml


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
  <display-name>spring-jpa</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  
   <!-- 开启编码过滤器 -->
	<filter>
		<description>字符集过滤器</description>
		<filter-name>encodingFilter</filter-name>
		<filter-class>
		    org.springframework.web.filter.CharacterEncodingFilter
		</filter-class>
		<init-param>
			<description>字符集编码</description>
			<param-name>encoding</param-name>
			<param-value>UTF-8</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>encodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	<!-- Spring的监听器 -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:applicationContext-redis.xml,classpath:spring.xml</param-value>
	</context-param>
	<listener>
	    <listener-class>
	        org.springframework.web.context.ContextLoaderListener
	    </listener-class>
	</listener>
	
	<!-- 配置SpringMVC的处理请求的Servlet -->
	<servlet>
		<servlet-name>dispatcherServlet</servlet-name>
		<servlet-class>
		    org.springframework.web.servlet.DispatcherServlet
		</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:springmvc.xml</param-value>
		</init-param>
		<!-- 表示系统启动时自动加载这个servlet -->
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>dispatcherServlet</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
	
	
	<!-- 设置是否支持put和delete请求 -->
	<filter>
		<filter-name>HiddenHttpMethodFilter</filter-name>
		<filter-class>
		     org.springframework.web.filter.HiddenHttpMethodFilter
		</filter-class>
	</filter>
	<filter-mapping>
	    <filter-name>HiddenHttpMethodFilter</filter-name>
	    <url-pattern>/*</url-pattern>
	</filter-mapping>
	
	<!-- 解决no session问题 -->
  <!-- <filter>
    <filter-name>noSessionFilter</filter-name>
    <filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>noSessionFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping> -->
  
</web-app>

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Spring Boot中使用Spring Data Redis进行Redis Geo操作,需要在pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>3.6.0</version> </dependency> ``` 然后在application.properties文件配置Redis相关信息: ```properties # Redis spring.redis.host=localhost spring.redis.port=6379 spring.redis.password= ``` 接下来,我们需要创建一个RedisGeoService来进行Geo操作: ```java @Service public class RedisGeoService { private final RedisTemplate<String, String> redisTemplate; public RedisGeoService(RedisTemplate<String, String> redisTemplate) { this.redisTemplate = redisTemplate; } /** * 添加地理位置信息 * * @param key 键 * @param longitude 经度 * @param latitude 纬度 * @param member 成员 * @return Long */ public Long add(String key, double longitude, double latitude, String member) { Point point = new Point(longitude, latitude); return redisTemplate.opsForGeo().add(key, point, member); } /** * 获取两个地理位置的距离 * * @param key 键 * @param member1 成员1 * @param member2 成员2 * @param unit 距离单位 * @return Distance */ public Distance distance(String key, String member1, String member2, Metric unit) { return redisTemplate.opsForGeo().distance(key, member1, member2, unit); } /** * 获取指定成员的地理位置 * * @param key 键 * @param members 成员 * @return List<Point> */ public List<Point> position(String key, String... members) { return redisTemplate.opsForGeo().position(key, members); } /** * 获取指定地理位置附近的成员 * * @param key 键 * @param longitude 经度 * @param latitude 纬度 * @param radius 半径 * @param unit 距离单位 * @return GeoResults<GeoLocation<String>> */ public GeoResults<GeoLocation<String>> nearBy(String key, double longitude, double latitude, double radius, Metric unit) { Circle circle = new Circle(longitude, latitude, new Distance(radius, unit)); GeoRadiusCommandArgs args = GeoRadiusCommandArgs.newGeoRadiusArgs().sortAscending(); return redisTemplate.opsForGeo().radius(key, circle, args); } } ``` 上述代码中,我们使用了RedisTemplate来进行Redis操作。RedisTemplate是Spring Data Redis提供的核心组件,用于执行Redis命令。 在RedisGeoService中,我们定义了四个方法来进行Geo操作: - add方法:添加地理位置信息。 - distance方法:获取两个地理位置的距离。 - position方法:获取指定成员的地理位置。 - nearBy方法:获取指定地理位置附近的成员。 使用Spring Boot和Spring Data Redis进行Geo操作非常方便,只需要定义一个RedisGeoService,并注入RedisTemplate即可。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值