【Spring系列】Spring mvc整合redis(非集群)

深碍√TFBOYSˉ_ 2021-12-24 17:43 361阅读 0赞

一、在pom.xml中增加redis需要的jar包

  1. <!--spring redis相关jar包-->
  2. <dependency>
  3. <groupId>redis.clients</groupId>
  4. <artifactId>jedis</artifactId>
  5. <version>2.9.0</version>
  6. </dependency>
  7. <dependency>
  8. <groupId>org.springframework.data</groupId>
  9. <artifactId>spring-data-redis</artifactId>
  10. <version>1.8.9.RELEASE</version>
  11. </dependency>

二、准备redis.properties文件,位置在resources文件夹下

  1. redis.host=192.168.181.201
  2. redis.port=6379
  3. redis.pass=123456
  4. redis.timeout=-1
  5. redis.maxIdle=100
  6. redis.minIdle=8
  7. redis.maxWait=-1
  8. redis.testOnBorrow=true

三、在applicationContext.xml中增加集成redis的配置

  1. <!--集成redis-->
  2. <!--jedis配置-->
  3. <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
  4. <property name="maxIdle" value="100"/>
  5. <property name="minIdle" value="8"/>
  6. <property name="maxWaitMillis" value="-1"/>
  7. <property name="testOnBorrow" value="false"/>
  8. </bean>
  9. <!--redis服务器中心-->
  10. <bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
  11. <property name="poolConfig" ref="poolConfig"/>
  12. <property name="port" value="6379"/>
  13. <property name="hostName" value="192.168.181.201"/>
  14. <property name="password" value="123456"/>
  15. <property name="timeout" value="-1"/>
  16. </bean>
  17. <!--redis操作模板 面向对象的模板-->
  18. <bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">
  19. <property name="connectionFactory" ref="connectionFactory"/>
  20. <!--如果不配置Serializer 那么存储的时候只能使用String ,如果用对象类型存储,那么会提示错误-->
  21. <property name="keySerializer">
  22. <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
  23. </property>
  24. <property name="valueSerializer">
  25. <bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/>
  26. </property>
  27. </bean>

  

四、编写redis操作工具类

  1. package com.slp.util;
  2. import org.springframework.data.redis.core.StringRedisTemplate;
  3. import org.springframework.stereotype.Component;
  4. import javax.annotation.Resource;
  5. /**
  6. * @author sanglp
  7. * @create 2018-01-31 9:08
  8. * @desc 操作hash的工具类
  9. **/
  10. @Component("redisCache")
  11. public class RedisCacheUtil {
  12. @Resource
  13. private StringRedisTemplate redisTemplate;
  14. /**
  15. * 向Hash中添加值
  16. * @param key 可以对应数据库中的表名
  17. * @param field 可以对应数据库表中的唯一索引
  18. * @param value 存入redis中的值
  19. */
  20. public void hset(String key,String field,String value){
  21. if (key == null || "".equals(key)){
  22. return;
  23. }
  24. redisTemplate.opsForHash().put(key,field,value);
  25. }
  26. /**
  27. * 从redis中取出值
  28. * @param key
  29. * @param field
  30. * @return
  31. */
  32. public String hget(String key,String field){
  33. if (key == null || "".equals(key)){
  34. return null;
  35. }
  36. return (String)redisTemplate.opsForHash().get(key,field);
  37. }
  38. /**
  39. * 查询key中对应多少条数据
  40. * @param key
  41. * @param field
  42. * @return
  43. */
  44. public boolean hexists(String key,String field){
  45. if(key == null|| "".equals(key)){
  46. return false;
  47. }
  48. return redisTemplate.opsForHash().hasKey(key,field);
  49. }
  50. /**
  51. * 删除
  52. * @param key
  53. * @param field
  54. */
  55. public void hdel(String key,String field){
  56. if(key == null || "".equals(key)){
  57. return;
  58. }
  59. redisTemplate.opsForHash().delete(key,field);
  60. }
  61. }

  

五、使用junit进行测试

  1. package com.slp;
  2. import com.slp.util.RedisCacheUtil;
  3. import org.junit.Before;
  4. import org.junit.Test;
  5. import org.springframework.context.ApplicationContext;
  6. import org.springframework.context.support.FileSystemXmlApplicationContext;
  7. /**
  8. * @author sanglp
  9. * @create 2018-01-31 9:16
  10. * @desc redis测试类
  11. **/
  12. public class RedisTest {
  13. private RedisCacheUtil redisCache;
  14. private static String key;
  15. private static String field;
  16. private static String value;
  17. @Before
  18. public void setUp() throws Exception {
  19. //ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("D:/web-back/web-back/myweb/web/WEB-INF/applicationContext.xml");
  20. //context.start();
  21. String path="web/WEB-INF/applicationContext.xml";
  22. ApplicationContext context = new FileSystemXmlApplicationContext(path);
  23. redisCache = (RedisCacheUtil) context.getBean("redisCache");
  24. }
  25. // 初始化 数据
  26. static {
  27. key = "tb_student";
  28. field = "stu_name";
  29. value = "一系列的关于student的信息!";
  30. }
  31. // 测试增加数据
  32. @Test
  33. public void testHset() {
  34. redisCache.hset(key, field, value);
  35. System.out.println("数据保存成功!");
  36. }
  37. // 测试查询数据
  38. @Test
  39. public void testHget() {
  40. String re = redisCache.hget(key, field);
  41. System.out.println("得到的数据:" + re);
  42. }
  43. // 测试数据的数量
  44. @Test
  45. public void testHsize() {
  46. //long size = redisCache.hsize(key);
  47. // System.out.println("数量为:" + size);
  48. }
  49. }

六、在项目中简单使用  

  1. package com.slp.web;
  2. import com.slp.dto.UserInfo;
  3. import com.slp.service.UserInfoService;
  4. import com.slp.util.EHCacheUtil;
  5. import com.slp.util.RedisCacheUtil;
  6. import net.sf.ehcache.CacheManager;
  7. import org.apache.log4j.Logger;
  8. import org.springframework.beans.factory.annotation.Autowired;
  9. import org.springframework.stereotype.Controller;
  10. import org.springframework.ui.ModelMap;
  11. import org.springframework.web.bind.annotation.RequestMapping;
  12. import org.springframework.web.bind.annotation.RequestMethod;
  13. import javax.servlet.http.HttpServletRequest;
  14. import java.util.List;
  15. /**
  16. * @author sanglp
  17. * @create 2018-01-23 9:04
  18. * @desc 登陆入口
  19. **/
  20. @Controller
  21. public class LoginController {
  22. private Logger logger= Logger.getLogger(this.getClass());
  23. @Autowired
  24. private UserInfoService userInfoService;
  25. @Autowired
  26. private CacheManager cacheManager;
  27. @Autowired
  28. private RedisCacheUtil redisCacheUtil;
  29. /**
  30. * 进入登陆首页页面
  31. * @param map
  32. * @return
  33. */
  34. @RequestMapping(value = "login",method = {RequestMethod.POST,RequestMethod.GET})
  35. public String login(ModelMap map){
  36. //进入登陆页面
  37. return "login";
  38. }
  39. /**
  40. * 获取用户信息监测是否已注册可以登录
  41. * @param map
  42. * @param request
  43. * @return
  44. */
  45. @RequestMapping(value = "loginConfirm",method = {RequestMethod.POST,RequestMethod.GET})
  46. public String loginConfirm(ModelMap map, HttpServletRequest request){
  47. EHCacheUtil.put("FirstKey",request.getParameter("email") );
  48. //登陆提交页面
  49. String email = request.getParameter("email");
  50. logger.info("email="+email);
  51. String password = request.getParameter("password");
  52. logger.info("password="+password);
  53. UserInfo userInfo = new UserInfo();
  54. userInfo.setEmail(email);
  55. userInfo.setUserPassword(password);
  56. UserInfo user= userInfoService.selectUserByEmail(userInfo);
  57. String userEmail = redisCacheUtil.hget("userInfo","email");
  58. logger.debug("userEmail in redis cache is = "+userEmail);
  59. if(null == userEmail){
  60. redisCacheUtil.hset("userInfo","email",email);
  61. }
  62. if (user==null){
  63. return "signUp";
  64. }
  65. List keys = EHCacheUtil.getKeys();
  66. for(int i=0;i<keys.size();i++){
  67. logger.debug(keys.get(i));
  68. logger.debug(EHCacheUtil.get(keys.get(i)));
  69. }
  70. logger.info(user.getEmail());
  71. logger.info(user.getId());
  72. if(!user.getUserPassword().equals(password)){
  73. map.addAttribute("msg","请输入正确的密码");
  74. return "login";
  75. }else {
  76. request.getSession().setAttribute("email",user.getEmail());
  77. request.getSession().setAttribute("userName",user.getUserName());
  78. request.getSession().setAttribute("userId",user.getId());
  79. logger.info("校验通过");
  80. return "index";
  81. }
  82. }
  83. }

日志截图:

 775114-20180202110300046-1371347009.png

775114-20180202110310343-1585925060.png  

转载于:https://www.cnblogs.com/dream-to-pku/p/8404136.html

发表评论

表情:
评论列表 (有 0 条评论,361人围观)

还没有评论,来说两句吧...

相关阅读