springboot與redis整合案例(下)

pom.xml中
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.bwie</groupId>
	<artifactId>zhoukao03</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>zhoukao03</name>
	<description>Demo project for Spring Boot</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.5.6.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>

		<!--  <!–redis–>-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-redis</artifactId>
			<version>1.3.1.RELEASE</version>
		</dependency>

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

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>
		<!-- <!– 熱啓動  Shift+Ctrl+Alt+/ 配置–>
         <!–熱啓動的觸發條件是:編譯  Ctrl+Shift+F9–>

         <!– mybatis–>-->
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>1.1.1</version>
		</dependency>

		<!-- <!– mySql–>-->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
		</dependency>


		<!--<!–freemarker–>-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-freemarker</artifactId>
		</dependency>




		<!-- <!–jpa  簡化數據訪問–>-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>



		<!-- <!– import lombok –>-->
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<version>1.16.8</version>
			<scope>provided</scope>
		</dependency>


	</dependencies>


	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>


</project>

application.properties中的配置

spring.datasource.url =jdbc:mysql://localhost:3306/***_test

spring.datasource.username = root

spring.datasource.password = root

spring.datasource.driverClassName =com.mysql.jdbc.Driver

spring.datasource.max-active=20

spring.datasource.max-idle=8

spring.datasource.min-idle=8

spring.datasource.initial-size=10

#設定ftl文件路徑
spring.freemarker.template-loader-path=classpath:/templates
#啓動request對象在模版中的使用
spring.freemarker.request-context-attribute=request
#設定靜態資源
spring.mvc.static-path-pattern=/**
#默認的頁面後綴爲.ftl  可以修改爲.html
server.port=8080
server.context-path=/xiangmu
mybatis.type-aliases-package=com.bwie.pojo


#redis配置
spring.redis.host=192.168.202.132
spring.redis.port=6379

list.ftl中
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8"/>
    <title></title>
<#assign ctx = request.contextPath />

    <script type="text/javascript" src="jquery-1.10.1.js"></script>
    <script type="text/javascript">
        $(function () {

            var acounts = [];
            $(".aa").click(function () {
                var acount = $(this).prev().val();
                if(acount==0){
                    acount=0;
                }else{
                    acount--;
                }

                $(this).prev().val(acount);

            });
            $(".bb").click(function () {

                var acount = $(this).prev().val();
                acount++;
                $(this).prev().val(acount);
            });

            $("input[type='button']").click(function () {
                var s = [];
                var acounts = [];
                var id = $("#id").val();
                $("input[name='gids']:checked").each(function () {
                    s.push($(this).val());
                    var acount = $(this).parent().next().next().next().children().eq(1).val();
                    acounts.push(acount);
                });

                window.location.href = "/xiangmu/save?uid=" + id + "&id=" + s + "&acounts=" + acounts;
            });

        });
    </script>
</head>

<body>

<#if name?exists>
${name}
</#if>

<table border="1" style="background-color: brown">
    <tr>
        <td>請選擇<input id="id" type="hidden" name="id" value="${uid}"/></td>
        <td>商品名稱</td>
        <td>商品單價</td>
        <td>商品數量</td>

    </tr>

<#list goods as g>
    <tr>
        <td><input type="checkbox" name="gids" value="${g.id}"/></td>
        <td>${g.gname}</td>
        <td>${g.price}</td>
        <td>

            <button class="aa">-</button>
            <input class="c" type="text" name="goods_acount" value="${g.acount}"/>
            <button class="bb">+</button>
        </td>

    </tr>
</#list>
</table>
<input type="button" value="保存"/>

</body>
</html>
Mapper接口中
package com.bwie.dao;

import com.bwie.pojo.Goods;
import com.bwie.pojo.Order;
import com.bwie.pojo.User;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * Created by Administrator on 2017/8/21.
 */
@Mapper
public interface UserMapper {


    @Insert("insert into t_user (username,password)values(#{username},#{password})")
    public void insert(User user);

    @Select("select * from t_user where username=#{username} and password=#{password}")
public User login(User user);

    @Select("select * from t_goods ")
    public List<Goods> selectGoods();

    @Select("select * from t_user where username=#{username}")
    public User selectByName(String username);

    @Select("insert into  t_order (user_id,goods_id,goods_acount)values(#{user_id},#{goods_id},#{goods_acount})")
    public void save(Order order);


}
controller層
package com.bwie.controller;

import com.bwie.pojo.Goods;
import com.bwie.pojo.Order;
import com.bwie.pojo.User;
import com.bwie.service.UserService;
import com.bwie.util.JedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import redis.clients.jedis.Jedis;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * Created by Administrator on 2017/8/21.
 */

@Controller
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("insert")
    public String insert(User user, HttpServletRequest request){

        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //將username和password封裝成一個user對象,保存到數據庫中
           user.setUsername(username);
        user.setPassword(password);
             userService.insert(user);
        //將username作爲鍵,將password作爲值,存入到redis數據庫中
        Jedis jedis = JedisUtils.getJedis();
        jedis.set(username,password);

        return "login";
    }

    @RequestMapping("toinsert")
    public String toinsert(){
        return "insert";
    }

    @RequestMapping("login")
    public String login(User user, HttpServletRequest request, HttpSession session){
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        //獲取jedis對象
        Jedis jedis = JedisUtils.getJedis();
        //根據username從redis數據庫中查詢對應的值
        String pwd = jedis.get(username);
        User user1 = userService.selectByName(username);
        System.out.println("---------------------"+user1.getId());
        if(pwd != null && pwd.equals(password)){
            session.setAttribute("uid",user1.getId());
            session.setAttribute("name",username);
            return "redirect:select";
        }else{
            session.setAttribute("mess","y用戶名或密碼錯誤");
            return "login";
        }

    }

    @RequestMapping("select")
    public String select(Model model){
        List<Goods> goods = userService.selectGoods();
        model.addAttribute("goods",goods);
        return "list";
    }

    @RequestMapping("save")
    public String save(Model model,int uid,String [] id,String acounts []){
        System.out.println(acounts.toString());
        for (int i=0;i<id.length;i++
             ) {
            Order order = new Order();
            order.setUser_id(uid);
            order.setGoods_id(Integer.parseInt(id[i]));
            System.out.println(Integer.parseInt(acounts[i]));
            order.setGoods_acount(Integer.parseInt(acounts[i]));
            userService.save(order);
        }
        return "ok";
    }

}

utils包連接redis的方法
package com.bwie.util;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class JedisUtils {
    /*
    redis的第一種連接方法
     */
    private final static JedisPool POOL;
    static {
        JedisPoolConfig config = new JedisPoolConfig();

        config.setMaxTotal(50);
        config.setMaxIdle(10);

        POOL = new JedisPool(config, "192.168.202.132", 6379);
    }
    public static Jedis getJedis() {
        return POOL.getResource();
    }
}

package com.bwie.util;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import javax.annotation.PostConstruct;

/**
 * Created by Administrator on 2017/8/22.
 */
@Component
public class JedisUtils_2 {

    /*
    第二種連接redis的方法
     */
    @Value("${spring.redis.host}")
    private String redisHost;
    @Value("${spring.redis.port}")
    private Integer redisPort;

    private JedisPool POOL;

    @PostConstruct
    public void initJedisPool() {

        JedisPoolConfig config = new JedisPoolConfig();

        config.setMaxTotal(50);
        config.setMaxIdle(10);

        POOL = new JedisPool(config, redisHost, redisPort);
    }


    @Bean
    public Jedis getJedis() {
        return POOL.getResource();
    }

}






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章