Redis代码指南第二章

代码指南主要记住几步:
1.建project
2.改pom
3.改yml(properties)
4.主启动类
5业务类

1.新建project redis
2.pom.xml


4.0.0

org.springframework.boot
spring-boot-starter-parent
2.5.1


com.yemers
redis
0.0.1-SNAPSHOT
redis
Demo project for Spring Boot

1.8



redis.clients
jedis
3.2.0



org.springframework.boot
spring-boot-starter-data-redis

	
	
		org.apache.commons
		commons-pool2
		2.6.0
	

	
		org.springframework.boot
		spring-boot-starter-security
	

	
		org.springframework.boot
		spring-boot-starter-websocket
	
	
		cn.hutool
		hutool-all
		5.7.0
	

	
		org.springframework.boot
		spring-boot-starter-thymeleaf
	
	
		org.springframework.boot
		spring-boot-starter-web
	
	
		org.thymeleaf.extras
		thymeleaf-extras-springsecurity5
	
	
		org.springframework.boot
		spring-boot-starter-test
		test
	
	
		org.springframework.security
		spring-security-test
		test
	
	
		org.projectlombok
		lombok
		1.18.10
	
	
	
		     org.springframework.boot
		     spring-boot-devtools
	



	
		
			org.springframework.boot
			spring-boot-maven-plugin
		
	

**3.我这边使用的是properties 使用yml一样** #指定开发版本properties --application.properties spring.profiles.active=dev #引入spring security 指定用户名 密码 这里为了方便没有写 登录页与后台继承类只为了验证redis spring.security.user.name=song spring.security.user.password=song --application-dev.properties

#Redis服务器地址
spring.redis.host=192.168.162.134
#Redis服务器连接端口
spring.redis.port=6379
#Redis数据库索引(默认为0)
spring.redis.database= 0
#连接超时时间(毫秒)
spring.redis.timeout=1800000
#连接池最大连接数(使用负值表示没有限制)
spring.redis.lettuce.pool.max-active=20
#最大阻塞等待时间(负数表示没限制)
spring.redis.lettuce.pool.max-wait=-1
#连接池中的最大空闲连接
spring.redis.lettuce.pool.max-idle=5
#连接池中的最小空闲连接
spring.redis.lettuce.pool.min-idle=0

server.port=8088
server.servlet.context-path=/redis
– 启用hiddenMethod过滤器
spring.mvc.hiddenmethod.filter.enabled=true
#关闭页面缓存# 模板编码 # 页面映射路径 # 试图后的后缀 # 模板模式
spring:
thymeleaf:
cache: false
encoding: UTF-8
prefix: classpath:/templates/
suffix: .html
mode: HTML5

4主启动类RedisApplication
/***
*@SpringBootApplication 等于三个 springbootconfiguration enableautoconfiguration compoentsacn
*springbootapplication 默认扫描的路径是主程序下的包路径

  • 改路径的话
  • */
    @SpringBootApplication
    public class RedisApplication {
    public static void main(String[] args) {
    SpringApplication.run(RedisApplication.class, args);
    }
    }

5 业务类
config配置类 RedisConfig

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;
import java.util.Arrays;

/**

  • Created by admin on 2021/6/15.
    */
    @EnableCaching
    @Configuration
    public class RedisConfig extends CachingConfigurerSupport {

    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory factory) {
    RedisTemplate template = new RedisTemplate<>();
    RedisSerializer redisSerializer = new StringRedisSerializer();
    Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
    ObjectMapper om = new ObjectMapper();
    om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
    om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
    jackson2JsonRedisSerializer.setObjectMapper(om);
    template.setConnectionFactory(factory);
    //key序列化方式
    template.setKeySerializer(redisSerializer);
    //value序列化
    template.setValueSerializer(jackson2JsonRedisSerializer);
    //value hashmap序列化
    template.setHashValueSerializer(jackson2JsonRedisSerializer);
    return template;
    }

    @Bean
    public CacheManager cacheManager(RedisConnectionFactory factory) {
    RedisSerializer redisSerializer = new StringRedisSerializer();
    Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
    //解决查询缓存转换异常的问题
    ObjectMapper om = new ObjectMapper();
    om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
    om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
    jackson2JsonRedisSerializer.setObjectMapper(om);
    // 配置序列化(解决乱码的问题),过期时间600秒
    RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
    .entryTtl(Duration.ofSeconds(600))
    .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
    .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
    .disableCachingNullValues();
    RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
    .cacheDefaults(config)
    .build();
    return cacheManager;
    }

}

#登录Controller
@Controller
public class IndexController {

@RequestMapping("/")
public String index(){
    System.out.println("index()进入----");
    //return "index";
    //重定向到main请求
    return "redirect:/main";
}
@RequestMapping("/main")
public String main(){
    System.out.println("---------欢迎进入Redis的世界!-------------------");
    return "/page/main";
}

}
#登录成功跳转
@Controller
@RequestMapping("/student")
public class RedisController {

@Autowired
private RedisTemplate redisTemplate;


@RequestMapping("/save")
@ResponseBody
public String  saveRedis(HttpServletRequest request){
    Student student=new Student();
    String name=request.getParameter("name");
    String age=request.getParameter("age");
    String score=request.getParameter("score");

    student.setName(name);
    student.setAge(Integer.valueOf(age));
    student.setScore(Double.valueOf(score));
    List list=new ArrayList<>();
    //list.add(student);

    redisTemplate.opsForValue().set("student",student);
    return "success";

}

//获取登录二维码、放入Token
@RequestMapping(value = "/getLoginQr" ,method = RequestMethod.GET)
public void createCodeImg(HttpServletRequest request, HttpServletResponse response){
    response.setHeader("Pragma", "No-cache");
    response.setHeader("Cache-Control", "no-cache");

    response.setDateHeader("Expires", 0);
    response.setContentType("image/jpeg");

    try {
        //这里没啥操作 就是生成一个UUID插入 数据库的表里
        //String uuid = userService.createQrImg();
        String uuid = UUID.randomUUID().toString();    //转化为String对象
        uuid = uuid.replace("-", "");
        response.setHeader("uuid", uuid);
        // 这里是开源工具类 hutool里的QrCodeUtil
        // 网址:http://hutool.mydoc.io/
        QrCodeUtil.generate(uuid, 300, 300, "jpg",response.getOutputStream());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

/**
 * 确认身份接口:确定身份以及判断是否二维码过期等
 * @param token
 * @param userId
 * @return
 */
@RequestMapping(value = "/bindUserIdAndToken" ,method = RequestMethod.GET)
@ResponseBody
public Object bindUserIdAndToken(@RequestParam("token") String token ,
                                 @RequestParam("userId") Integer userId,
                                 @RequestParam(required = false,value = "projId") Integer projId){

   /* try {
        return new SuccessTip(userService.bindUserIdAndToken(userId,token,projId));
    } catch (Exception e) {
        e.printStackTrace();
        return new ErrorTip(500,e.getMessage());
    }*/
    return null;
}

}

页面:

欢迎进入Redis世界

欢迎进入Redis世界

进入主页面
Title

欢迎进入Redis世界!

你可能感兴趣的:(redis,java)