redis整合springboot01

1.redis依赖

    <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

2、redis关于yml配置

  redis:
    host: 127.0.0.1
    port: 6379

3、service

import com.example.vuetest01.library.entity.Userregister;
import com.baomidou.mybatisplus.extension.service.IService;

/**
 * <p>
 *  服务类
 * </p>
 *
 * @author IJun
 * @since 2021-01-20
 */
public interface UserregisterService extends IService<Userregister> {
    public Object  userLogin(Userregister userregister);
}

  

5、serviceImpl层

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.vuetest01.library.entity.Userregister;
import com.example.vuetest01.library.mapper.UserregisterMapper;
import com.example.vuetest01.library.service.UserregisterService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author IJun
 * @since 2021-01-20
 */
@Service
public class UserregisterServiceImpl extends ServiceImpl<UserregisterMapper, Userregister> implements UserregisterService {
    @Autowired
    private UserregisterMapper mapper;
    @Autowired
    @Qualifier("redisTemplates")
    private RedisTemplate redisTemplate;
    @Override
    public Userregister userLogin(Userregister userregister) {
      //  JSONObject jsonObject=new JSONObject();
        //封装redis一个对象
        BoundValueOperations users = redisTemplate.boundValueOps("users");
         Userregister o = (Userregister) users.get();
        if (o == null){
            //数据库查询
            QueryWrapper<Userregister> wrapper=new QueryWrapper<>();
            wrapper.eq("username",userregister.getUsername());
            Userregister userregister1= mapper.selectOne(wrapper);
            if ( userregister1 == null){
                throw new RuntimeException("登录用户名不存在");
            }
            if (! userregister1.getPassword().equals(userregister.getPassword())){
                throw new RuntimeException("登录密码输入错误");
            }
            //顺便存入redis中
            users.set(userregister1);
            System.out.println("从数据据中取值...");
            return userregister1;
        }else {
            System.out.println("从缓存中获取数据...");
            return o;
        }
    }
}

6、controller

import com.alibaba.fastjson.JSONObject;
import com.example.vuetest01.library.entity.Userregister;
import com.example.vuetest01.library.service.UserregisterService;
import com.example.vuetest01.library.utils.Consts;
import com.example.vuetest01.library.utils.JWTUtils;
import com.example.vuetest01.library.utils.Md5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author IJun
 * @since 2021-01-20
 */
@Controller
public class UserregisterController {
  @Autowired
  private   UserregisterService userregisterService;
   @PostMapping("/register")
   @ResponseBody
   @CrossOrigin
    public void ss(@RequestBody @Validated Userregister userregister ){
       System.out.println("前端传的用户名"+userregister.getUsername());
       System.out.println("前端传的密码"+userregister.getPassword());
       System.out.println("执行成功!");
       System.out.println(Md5Utils.inputPassToDBPass(userregister.getPassword(), "zxc123"));
       userregister.setPassword(Md5Utils.inputPassToDBPass(userregister.getPassword(), "zxc123"));
       userregisterService.saveOrUpdate(userregister);
   }
    @GetMapping("/login")
    @ResponseBody
    //@CrossOrigin @RequestBody @Validated
   public Object login( Userregister userregister){
     //   session.setAttribute(Consts.NAME,userregister.getUsername());
        System.out.println("进入login...");
        JSONObject jsonObject=new JSONObject();
        Map<String,Object> map=new HashMap<>();
        try {
            Userregister userregister1 = (Userregister) userregisterService.userLogin(userregister);
            //------------token
            Map<String,String> map1=new HashMap<>();
            map1.put("username",userregister1.getUsername());
            map1.put("password",userregister1.getPassword());
            String token = JWTUtils.getToken(map1);

            jsonObject.put(Consts.CODE,201);
            jsonObject.put(Consts.MSG,"认证成功");
            jsonObject.put("token",token);// --------------------
        } catch (Exception e) {
            jsonObject.put(Consts.CODE,500);
            jsonObject.put(Consts.MSG,"认证失败");
        }
        return jsonObject;
    }

    @PostMapping("/user/test")
    @ResponseBody
    public Object testq(){
       JSONObject jsonObject=new JSONObject();
       //处理自己的业务逻辑
        jsonObject.put(Consts.CODE,666);
        jsonObject.put(Consts.MSG,"啦啦啦!德玛西亚");
        return jsonObject;
    }
}

7、可视化工具、redis客户端获取数据需要序列化redisConfig

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.StringRedisSerializer;

@Configuration
public class RedisConfig {

    @Bean(name = "redisTemplates")
    @SuppressWarnings("all")
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {

        RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();

        template.setConnectionFactory(factory);

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

        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        // key采用String的序列化方式

        template.setKeySerializer(stringRedisSerializer);

        // hash的key也采用String的序列化方式

        template.setHashKeySerializer(stringRedisSerializer);

        // value序列化方式采用jackson

        template.setValueSerializer(jackson2JsonRedisSerializer);

        // hash的value序列化方式采用jackson

        template.setHashValueSerializer(jackson2JsonRedisSerializer);

        template.afterPropertiesSet();

        return template;

    }
}

8、

 

posted @ 2021-01-28 21:46  iJunHello  阅读(91)  评论(0)    收藏  举报